Laravel 5.6 - 高效获取关系计数和 updated_at 列的最后一个值

Laravel 5.6 - Efficiently get relation count and last value of updated_at column

假设我将 PostsComments 定义为:

Post.php

public function comments()
{
  return $this->hasMany('App\Comment');
}

Comment.php

public function post()
{
  return $this->belongsTo('App\Post');
}

我想用 number of comments 和最后更新的评论的 updated_at 列有效地加载 Post。我将如何进行?

我能想到的最好的办法是加载 Post 所有评论,但将评论的 select 限制在 post_idupdated_at 列。然后在视图中计算加载的评论以获取计数并使用 sortByDesc('updated_at')->first() 获取最后一列的日期:

MyController.php

Post::with([
  'comments' => function($q) {
    $q->select('post_id','updated_at');
  }
])->get();

my_view.blade.php

Comments count: {{ $posts->comments->count() }}
Last comment: {{ $posts->comments->sortByDesc('updated_at')->first()->updated_at }}

有没有办法更有效地做到这一点,并且只获取最新 comments.updated_at 列的评论数和价值?

MySQL或Eloquent解决即可。

谢谢!

您可以通过 withCount() 实现两者:

Post::withCount([
    'comments',
    'comments as last_comment' => function($q) {
        $q->select(DB::raw('max(updated_at)'));
    }
])->get();

Comments count: {{ $post->comments_count }}
Last comment: {{ $post->last_comment }}