问题
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