Laravel. How to get relationships where foreign key is an array

送分小仙女□ 提交于 2019-12-24 02:14:46

问题


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


回答1:


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');
}


来源:https://stackoverflow.com/questions/49048041/laravel-how-to-get-relationships-where-foreign-key-is-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!