我有论坛,每个论坛都有很多帖子,每个帖子都有很多评论。帖子属于该论坛,评论属于这些帖子。
我正在尝试返回该论坛及其每个帖子以及每个帖子的每条评论。这是我最终得到的代码:
public function showposts($id)
{
$forum = Forum::find($id);
$comments = $forum->posts->each(function($post)
{
$comment = $post->comments;
});
return response()->json($forum, 201);
}
我不明白的是为什么会这样。
如果我不包括$comments部分,那么它只会返回没有任何帖子或评论的论坛,如果我删除循环,那么只有论坛和帖子将返回而不发表评论。
不过,我仍然只返回论坛,$comments根本没有包括在内,但它会影响它。谁能解释一下这里发生了什么?
它之所以有效,是因为调用$forum->posts
会延迟加载论坛相关帖子。调用每个$post->comments
将延迟加载与帖子相关的评论。
一种更优雅和高性能的方法是预先加载关系:
public function showposts($id)
{
$forum = Forum::with('posts.comments')->find($id);
return response()->json($forum, 201);
}