任何人都可以帮助我编写查询以从我的单词表中检索单词,使单词通过类型数据透视表与类型模型具有 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
来自 types 表,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 个项目的数组。
感谢您的阅读,我将不胜感激任何提示或帮助。
最佳答案
您可以提供数据透视表:
public $belongsToMany = [
'typeswb' => [
'Yeoman\Wordbank\Models\Type',
'table'=>'yeoman_wordbank_types_pivotb',
'key' =>'word_id ',
'otherKey' => 'type_id ',
'pivot' => ['word_id ', 'type_id '],
],
];
关于php - 通过数据透视表 Octobercms 从表中检索条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44845027/