0

我如何在 Laravel 中处理这种情况:

我有模型新闻,每个新闻都属于一个用户:

class News extends Model {
(...)

    public function user()
    {
        return $this->belongsTo(User::class, 'author_user_id');
    }

(...)

我也有一个评论模型,而且每条评论都属于一个用户:

class Comment extends Model {
(...)

    public function user()
    {
        return $this->belongsTo(User::class);
    }

(...)
}

在 NewsController 的显示功能中,我收到带有评论的新闻:

    public function show($id)
    {

        $news = News::with('user', 'comments.user')->where('id', $id)->first();

        return view('news.show', compact(['news']));
    }

这工作得很好。问题是,我对同一个用户有很多请求。它查询新闻的子查询和相同 user_id 的评论的子查询。

这个对吗?我该如何优化呢?

此致

更新

显示函数如下所示:

        $news = News::with(
            'user:id,name',
            'comments:id,commentable_id,content,ip,user_id,created_at,updated_at',
            'comments.user:id,name',
            'comments.replies:id,commentable_id,parent_id,content,ip,user_id,created_at,updated_at',
            'comments.replies.user:id,name', 'comments.replies.user.media:id',
            'comments.user.media:id',
            'comments.reactions:user_id,comment_id,reaction', 'comments.replies.reactions:user_id,comment_id,reaction')
            ->where('id', $id)
            ->first(['id', 'heading', 'author_user_id', 'content', 'created_at', 'updated_at']);

        return view('news.show', compact(['news']));
4

0 回答 0