如何在Laravel中将'hasManyThrough'与3个以上的表一起使用? [英] How to use 'hasManyThrough' with more than 3 tables in Laravel?
问题描述
当前当您有 country>之类的内容时,可以使用hasManyThrough
.用户>帖子
as stated in the docs the current hasManyThrough can be used when u have something like country > users > posts
这会导致类似 Country :: whereName('xx')-> posts;
太好了,但是如果我还有更多类似的东西
which result in something like Country::whereName('xx')->posts;
which is great but what if i have more than that like
国家>城市>用户>帖子
甚至
国家>城市>城镇用户>帖子
然后您将如何实现类似的内容,以便您可以编写与上面相同的内容
how would you then implement something like that so you can write the same as above
Country :: whereName('xx')->帖子;
或 Town :: whereName('xx')-> posts;
推荐答案
遗憾的是,没有一个简单的解决方案,所以这就是我所发现的
sadly there is no one easy solution, so heres what i found
1-将另一张表的外部ID添加到发布表中,并坚持 hasMany &属于,例如
1- add the other table foreign id into the post table and stick to the hasMany & belongsTo, ex.
posts
id - integer
country_id - foreign
// etc...
title - string
2-在每个表上都使用 hasManyThrough ,除了 user
和& post
,因为除非您想深入了解,否则没有必要.
2- go with the hasManyThrough on each table except user
& post
as there is no need unless you want to go deeper, ex.
countries
id - integer
name - string
cities
id - integer
country_id - foreign
name - string
towns
id - integer
city_id - foreign
name - string
users
id - integer
town_id - foreign
name - string
posts
id - integer
user_id - foreign
title - string
-因此,让我们尝试第二个选项
- so lets try with the 2nd option
1-设置您的很多和属于关系
2-在模型上设置 hasManyThrough .
3-要实现上述 Country :: whereName('xx')-> posts
的示例,我们向 country 模型中添加了另一种方法
3- to achieve the above example of Country::whereName('xx')->posts
we add another method to the country model
// because Country::find($id)->towns, return an array
// so to get all the posts we have to loop over that
// and return a new array with all the country posts
public function posts()
{
$posts = [];
foreach ($this->towns as $town) {
$posts[] = $town->posts;
}
return $posts;
}
4-整个操作都通过 foreign_id 进行,因此我们通过 id 而不是 名称 ,例如 Country :: find($ id)-> posts()
4- as the whole thing is working through the foreign_id so we search by the id instead of the name like Country::find($id)->posts()
这篇关于如何在Laravel中将'hasManyThrough'与3个以上的表一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!