Laravel eager loading with nested relationship

眉间皱痕 提交于 2021-02-17 03:09:44

问题


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.


回答1:


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

Quoting the docs:

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();

In your case

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


来源:https://stackoverflow.com/questions/30593596/laravel-eager-loading-with-nested-relationship

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