然后定义两个 belongsToMany() 关系型号:public function pages(){ return $this->belongsToMany(Page::class);}如果您不遵循Laravel命名约定在我的仓库中列出,并且您为数据透视表名称指定了自定义名称,也对其进行了定义:public function pages(){ return $this->belongsToMany(Page::class, 'custom_pivot_table');}I am trying to retrieve database rows with their relationships. However, the local key is an array. Let me explain using an example.Lets say I have a table of countries and a table of pages. Each country can have many pages. Each page can belong to multiple countries. I do not have the flexibility to change this schema.pages+-------------+-----------+| id | name | countries |+-------------+-----------+| 1 | Page 1 | 1 |+-------------+-----------+| 2 | Page 2 | 1,2,3 |+-------------+-----------+| 3 | Page 3 | 4,5,6 |+-------------+-----------+countries+----+----------------+| id | name | +----+----------------+| 1 | United States |+----+----------------+| 2 | United Kingdom |+----+----------------+| 3 | Germany |+----+----------------+| 4 | France |+----+----------------+| 5 | Hong Kong |+----+----------------+| 6 | Thailand |+----+----------------+| 7 | Belgium |+----+----------------+| 8 | Singapore |+----+----------------+My model and controller look something like:country public function pages(){ return $this->hasMany(Page::class, 'id', 'countries');}MemberController.php$countries = Country::with('pages')->get();This is returning all countries, but only Page 1 contains any relationships. Is there a way to retrieve relationships using a whereIn approach so all three countries will return appropriate pages?Thanks in advance 解决方案 Since Page can belong to many Countries, you need to create a pivot table called country_page and remove the countries column.Then define two belongsToMany() relationships in both models:public function pages(){ return $this->belongsToMany(Page::class);}If you're not following Laravel naming conventions listed in my repo and you gave the pivot name a custom name, define it too:public function pages(){ return $this->belongsToMany(Page::class, 'custom_pivot_table');} 这篇关于Laravel.如何在外键是数组的情况下获取关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-27 09:54