Laravel渴望通过嵌套关系加载 [英] Laravel eager loading with nested relationship

查看:61
本文介绍了Laravel渴望通过嵌套关系加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有人问过这个问题,但我的情况有所不同.我已将Post模型与Comment模型定义了关系:

I know this question has been asked but my situation is different. I have Post model with relationship to Comment model defined:

/*Post Model*/
public function comments(){
return $this->hasMany('comment');
}

和每个评论属于一个用户的评论模型:/评论模型/

and Comment model which each comment belong to one user : /comment model/

public function user(){
return $this->belongto('user');
}

现在,我想查询(每个帖子的)所有帖子和渴望加载的评论以及发布该评论的用户信息.无论如何要使它工作?谢谢.

now I want to query all post and eager load comments (of each post) along with user information who post the comment. anyway to make it work please ? thank you.

推荐答案

您想要的嵌套

What you want is nested eager loading, scroll down a bit and you will see it.

引用文档:

要急于加载嵌套关系,可以使用点"语法.为了例如,让我们急于加载本书的所有作者和所有一位雄辩的陈述中作者的个人联系方式:

To eager load nested relationships, you may use "dot" syntax. For example, let's eager load all of the book's authors and all of the author's personal contacts in one Eloquent statement:

$books = Book::with('author.contacts')->get();

以您的情况

$posts = Post::with('comments.user')->get();

这篇关于Laravel渴望通过嵌套关系加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆