【发布时间】:2020-03-22 06:52:53
【问题描述】:
假设我需要获得一个包含评论数的帖子。当然有很多方法可以做到这一点。这样做的最佳(或首选)方法是什么?
- Eager Load + 然后与路由模型绑定以在将模型注入路由时获取计数。
class Post extends Model {
protected $withCount = [ 'comments' ];
public function comments()
{
return $this->hasMany();
}
}
Route::get('/posts/{post}', function (App\Post $post) {
return $post; // $post→comments_count gives count.
}
- 缓存计数
public function getCachedCommentsCountAttribute()
{
return Cache::remember($this->getTable() . '.' . $this->getKey() . '.comments_count', 60*60*24, function () {
return $this->comments()->count(); // posts.{id}.comments_count
});
}
- 其他
最好的性能是什么?
【问题讨论】:
标签: laravel eloquent laravel-query-builder