假设我有
Posts
Comments
定义为:
public function comments()
{
return $this->hasMany('App\Comment');
}
注释.php
public function post()
{
return $this->belongsTo('App\Post');
}
我想有效地加载Post
number of comments
以及
updated_at
上次更新的注释的列。我该怎么做?
我能想到的最好的办法是加载包含所有评论的Post,但是将select-on-Comments限制为
post_id
更新时间
sortByDesc('updated_at')->first()
要获取最后一列的日期:
MyController.php
Post::with([
'comments' => function($q) {
$q->select('post_id','updated_at');
}
])->get();
我的视图.blade.php
Comments count: {{ $posts->comments->count() }}
Last comment: {{ $posts->comments->sortByDesc('updated_at')->first()->updated_at }}
comments.updated_at
专栏?
MySQL或雄辩的解决方案是可以的。
谢谢!