Laravel延迟加载优化

时间:2014-08-31 18:05:20

标签: php laravel orm query-optimization eloquent

我想用一个查询加载我的所有评论,现在我有论坛帖子和回复以及两者的评论,所以我急切地加载评论。

$threads = Thread::with('comments');
$replies = Reply::with('comments');

可能是这样的:

Comment::loadFor([$threads, $replies]);

1 个答案:

答案 0 :(得分:0)

如果你已经在Comment模型中声明了关系,那么你可以试试这个:

$comments = Comment::with('threads', 'replies')->get();

在这种情况下,您需要在threads模型中创建关系方法,例如repliesComment,例如:

public function replies()
{
    return $this->hasMany('Reply', 'comment_id', 'id'); // Could be different
}

public function threads()
{
    return $this->hasMany('Thread', 'comment_id', 'id'); // Could be different
}