【发布时间】:2017-06-30 11:08:16
【问题描述】:
谁能帮助我编写查询以从我的单词表中检索单词,使单词通过类型数据透视表与 Type 模型具有 belongsToMany 关系?
Word.php 中的关系如下所示
public $belongsToMany = [
'typeswb' => [
'Yeoman\Wordbank\Models\Type',
'table' => 'yeoman_wordbank_types_pivotb',
'order' => 'typesofwordbank'
]
];
这是类型表的样子
mysql> select * from yeoman_wordbank_types;
+----+--------------------+--------------------+
| id | typesofwordbank | slugoftypes |
+----+--------------------+--------------------+
| 1 | Common Words | common-words |
| 2 | Common Expressions | common-expressions |
| 3 | Common Proverbs | common-proverbs |
| 4 | Common Idioms | common-idioms |
+----+--------------------+--------------------+
4 rows in set (0.00 sec)
数据透视表的类型在哪里
mysql> select * from yeoman_wordbank_types_pivotb;
+---------+---------+
| word_id | type_id |
+---------+---------+
| 18 | 2 |
| 5 | 4 |
| 9 | 3 |
| 19 | 1 |
| 31 | 1 |
+---------+---------+
5 rows in set (0.00 sec)
如您所见,type_id 连接到 words_id。其中types_id's 来自类型表,words_id's 来自word 表。
我需要找到一种使用types_id 获取单词的方法。
我试过了
// $query = Word::all();
// foreach ($query->typeswb as $typeswb) {
// $queryy = $typeswb->pivot->type_id = 1;
// }
还有一些其他类似的组合,但都是徒劳的,奇怪的是我得到Word::find(1) null 而Word::all() 返回集合中6个项目的数组。
感谢您的阅读,我将非常感谢任何提示或帮助。
【问题讨论】:
-
您是否在您的
Types模型上定义了$belongsToMany? -
嗨@Meysam,正如你在问题的开头看到的那样,我做到了!
-
不,我在您的
Word模型中看到的是$belongsToMany。我在问Types模型。 -
@Meysam 不,我没有在
Types模型上定义任何反比关系,因为我只是想在我的Word模型上拥有belongToMany类型的关系。虽然,我已经解决了这个问题,请参阅我的答案:) 干杯! -
好吧,我认为您正在重新发明轮子。在
Types模型上定义反比关系将帮助您避免这种情况。
标签: php mysql laravel-5 octobercms