laravel遍历具有深厚关系的雄辩模型 [英] laravel looping through eloquent models with deep relationships
问题描述
以下循环有效:
foreach($this->friends as $friend)
{
foreach($friend->mailings as $mailing)
{
foreach($mailing->orders as $order)
{
$num_orders++;
}
}
}
但是想做
foreach($this->friends->mailings->orders as $order)
{
$num_orders++;
}
但是在执行此操作时出现此错误Property [mailings] does not exist on this collection instance.
but when I do I get this error Property [mailings] does not exist on this collection instance.
模型之间的关系已正确设置(有很多...等)
The relationship between models is setup correctly (has many...etc)
推荐答案
我找到了! Jarek是Eloquent的一位出色作家,我想看看他是否有技巧.和往常一样,他做到了. :)
I found it! Jarek is a great writer for Eloquent, and I wanted to see if he had a trick for this. As always he does. :)
$this->load(['friends.mailings.orders' => function($q) use(&$orders){
$orders = $q->get();
}]);
现在,如果您选择dd($orders)
,您将获得与$this
相关的朋友从邮件中收到的所有订单的列表,因此,您现在可以就此进行进一步的学习以获得想要的东西.
Now if you dd($orders)
you will have a list of all orders from mailings from friends related to $this
So you can now foreach over that to get what you want.
foreach($orders as $order){
$num_orders++
}
他的网站上有证书警告,但这是我获得上述警告的地方. https://softonsofa.com/laravel-querying -任何级别的亲戚关系都带有简单的技巧/
His site has a certificate warning but this is where I got the above. https://softonsofa.com/laravel-querying-any-level-far-relations-with-simple-trick/
请忽略以下内容,因为不再需要它,但为了清楚起见,我将其保留在此处,因为它已被接受为答案.
您可以使用each()
收集方法来清理循环.由于存在多对多关系,因此除非您对它们进行迭代或指定所需的相关项目,否则无法访问它们之间的关系.见下文:
You can use the each()
collection method to clean up your loops. Since there are many-to-many relationships you can't access the related models relations unless you iterate over them or specify which related item you want. See below:
$this->friends->each(function($friend, $key){
$friend->each(function($mailing, $key2){
$mailing->orders->each(function($orders, $key3){
$num_orders++;
})
});
})
https://laravel.com/docs/5.8/collections#method-each
您可能还需要研究withCount()
查询构建器方法.它似乎不喜欢使用常规点表示法的嵌套关系,但是我还没有足够使用它来说明是否可以在这里使用它.在查看hasManyThrough()
.它应该是一个不错的起点.
There's also the withCount()
query builder method that you may want to look into. It doesn't seem to like nested relations using the regular dot notation, but I haven't used it enough to say whether or not it can be used here. I stumbled upon Laravel 5.3 withCount() nested relation while looking into the withCount()
part. Seems like it may be possible but you will have to change your relations to hasManyThrough()
. It should be a good place to start.
这篇关于laravel遍历具有深厚关系的雄辩模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!