我想展示链接的评论和显示用户和用户配置文件的评论关系......
DD($ PAGE-> getRelation('链接'));
Collection {#318 ▼
#items: array:2 [▼
0 => Link {#317 ▼
#relations: array:2 [▼
"comments" => Collection {#327 ▼
#attributes: array:5 [▼
"id" => 3
"content" => "teste"
"link_id" => 1
"user_id" => 1
"created_at" => "2018-01-11 00:47:32"
]
#relations: array:2 [▼
"user" => User {#330 ▶}
"userProfile" => UserProfile {#326 ▶}
]
}
]
}
在我看来:
@foreach($page->getRelation('links') as $link)
<div class="link">
<!--show de comments of link (ONLY FOR EXPLANATION)-->
@foreach()
<div class="comments">
SHOW DE ATTRIBUTE OF COMMENT AND ATTRIBUTE OF RELATIONS OF COMMENT (user, userprofile)
</div>
@endforeach
</div>
@endforeach
答案 0 :(得分:0)
Eloquent可以在您查询父模型时“急切加载”关系。急切加载缓解了N + 1查询问题。 (...)查询时,您可以使用with方法指定哪些关系应该加载。
例如:
$pages = App\Page::with("link")->get();
foreach ($pages as $page) {
echo $page->links->comments;
}
您还可以加载多个关系
$pages = App\Page::with(['link', 'author'])->get();
最后,您可以嵌套急切的加载关系
o eager load嵌套关系,您可以使用“dot”语法。对于 让我们热切地加载这本书的所有作者和所有作者 作者在一个雄辩的声明中的个人联系
$pages = App\Page::with('link.comments')->get();
答案 1 :(得分:0)
首先加载控制器函数中的关系:
$page = Page::where($allYourConditions)->with(['links' =>
function($query){
$query->with(['comments' => function($query){
$query->with(['user', 'userProfile']);
}]);
}])->get();
然后在视图文件中:
@foreach($page->links as $link)
<div class="link">
@foreach($link->comments as $comment)
<div class="comment">
<div class="comment-user">{{$comment->user}}</div>
<div class="comment-user-profile">{{$comment->userProfile}}</div>
</div>
@endforeach
@endforeach