【发布时间】:2018-04-28 16:41:43
【问题描述】:
我只需要计数,不想每次都检索结果或执行查询。这就是我想要急切加载的原因。
我有 3 个如下表:
Admins
id
Posts
id
admin_id
Comments
id
user_id //nullable (null if comment from admin)
admin_id //nullable (null if comment from user)
news_id
现在我想从一个管理员那里检索所有帖子,并从这些帖子中计算所有 cmets,而不检索所有帖子的 cmets,仅计算 cmets, 急切加载以避免 n+1 查询问题;
在这里,我认为我们应该建立一个关系以用于急切加载,如下所示:
//admin model
public function commentsCountRelation()
{
return $this->hasManyThrough(Comment::class, News::class, 'admin_id', 'news_id')
->selectRaw('news_id, count(*) as count')
->groupBy('news_id');
}
--看这里我使用了hasManyThrough 关系,因为news_id 不在Admins 表中。
然后我应该创建一个属性,以便轻松访问计数,例如:
public function getCommentsCountAttribute()
{
return $this->commentsCountRelation->first()->count ?? 0;
}
然后像这样访问它:
$admin = Admin::with('commentsCountRelation')->findOrFail($id);
$admin->commentsCount;
但它总是返回null,这是为什么呢?
以下适用于hasMany 和belongsTo,我在其他型号上使用过,例如:
//relation
public function ordersCountRelation()
{
return $this->hasOne(Order::class)->selectRaw('user_id, count(*) as count')
->groupBy('user_id');
}
//attribute
public function getOrdersCountAttribute()
{
return $this->ordersCountRelation->count ?? 0;
}
//Then accessed like:
$user = User::with('ordersCountRelation')->find($id);
$user->ordersCount; //return only count
我们将不胜感激任何帮助
【问题讨论】:
标签: laravel count eloquent has-many-through eager-loading