[英]add an array of collection inside collection with Laravel 5.3
I need to get all clubs that belongs to a federationPresident. 我需要获取属于federationPresident的所有俱乐部。
So, I have: 所以我有:
$federation->associations
which gets me a collection of associations, 这使我得到了一些联想,
$association->clubs that gives me a collection of clubs
I would like to do : 我想要做 :
$federation->associations->clubs, but it doesn't work
What I did: 我做了什么:
foreach ($federation->associations as $association) {
foreach ($association->clubs as $club){
$clubs->push($club);
}
}
This works, but I think I'm missing something, and I could do it easilier. 这行得通,但我想我缺少了一些东西,而且我可以更轻松地做到这一点。
Thing is I will have to do it a lot of time in my code, so, this is not very elegant... 事情是我必须在代码中花很多时间,所以,这不是很优雅。
Any Idea how to do it better? 任何想法如何做得更好?
Association Model: 关联模型:
public function clubs()
{
return $this->hasMany(Club::class);
}
You can use eager loading. 您可以使用紧急加载。 You use dot notation to relate nested models. 您可以使用点表示法来关联嵌套模型。
$federations = Federation::with('associations.clubs')->get();
And now everything is nested for you... 现在一切都为您嵌套...
foreach ($federations as $federation) {
foreach ($federation->associations as $association) {
foreach ($assocation->clubs as $club) {
...
}
}
}
Another way would be to use the hasManyThrough
relating method. 另一种方法是使用hasManyThrough
相关方法。 It does work with 2 has-manies. 它确实可以处理2个has-manies。
In your Federation
model. 在您的Federation
模型中。
public function clubs()
{
return $this->hasManyThrough(Club::class, Association::class);
}
You can try the Has Many Through
relation ... 您可以尝试“ Has Many Through
关系...
which will get you all the clubs that belongs to the associations
of the federation
这将使您属于federation
associations
的所有俱乐部
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.