【问题标题】:Retrieve all posts and their most recent comments in 1 query在 1 个查询中检索所有帖子及其最新评论
【发布时间】:2017-10-19 13:55:48
【问题描述】:

我正在尝试检索(分页)帖子列表,并将他们最近的 cmets 包含在一个 Eloquent 查询语句中。 Posts 和 cmets 通过一对多的关系连接。

这是我的尝试:

Post::with(['comments' => function ($query) {
    $query->orderBy('created_at', 'asc')->take(3);
}])->simplePaginate(15);

但这只会检索 总共 3 个 cmets,而不是每个帖子 3 个 cmets。

【问题讨论】:

  • 我不认为 laravel 允许你限制急切加载的关系。我建议遍历 post 数组并加载 cmets,例如: $posts = Post::simplePaginate(15); foreach($posts as post) { $post->load(['cmets' => function($query) { $query->orderBy('created_at', 'asc')->take(3);}]) '

标签: php laravel eloquent query-builder


【解决方案1】:

需要加入的表ID
试试这个:

 Post::with(array('comments'=>function($query){
            $query->select('id as commentid','comment')->orderBy('created_at', 'asc')->take(3);
        }))->simplePaginate(15);

【讨论】:

  • 这对我没有任何结果。选择函数的第二个参数('comment')有什么用?
【解决方案2】:

更新

看来你不能用 1 个查询来做到这一点。
您仍然可以在父模型中使用此功能,称为“lastComments”:

function lastComments()
{
    return $this->hasMany('App\Post', 'post_id')->orderBy('created_at')->take(3);
}

您使用普通的雄辩代码加载帖子:

Post::simplePaginate(15);

在视图页面中,您以这种方式显示 cmets:

@foreach($post->lastComments as $comment)
    <!-- ... -->
@endforeach

【讨论】:

  • 据我所见,产生相同的结果,总共只加载了 3 个 cmets。
【解决方案3】:

您需要在App\Post 模型中设置$with 变量:

protected $with = ['lastComments'];

这样,每当您获取帖子时,Laravel 都会自动为其加载 cmets。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-18
    • 2021-07-13
    • 2014-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多