Laravel hasManyThrough与渴望加载的关系中的计数(仅需计数) 我只需要计数,不想每次检索结果或对每一行执行查询。这就是为什么我想要快速加载。
我有如下3张表:Laravel hasManyThrough与渴望加载的关系中的计数(仅需计数) 我只需要计数,不想每次检索结果或对每一行执行查询。这就是为什么我想要快速加载。,laravel,count,eloquent,has-many-through,eager-loading,Laravel,Count,Eloquent,Has Many Through,Eager Loading,我有如下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 //admin model public function commentsCountRelation()
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
//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');
}
现在我想从一个管理员那里检索所有帖子,所有评论都会从这些帖子中计数,而不检索帖子的所有评论,只计算评论数,
具有快速加载功能,避免n+1查询问题
在这里,我认为我们应该建立一个关系,以便与以下内容一起使用:
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
//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\u id不在Admins
表中
然后我应该创建一个属性,以便轻松访问计数,如:
public function getCommentsCountAttribute()
{
return $this->commentsCountRelation->first()->count ?? 0;
}
然后像这样访问它:
$admin = Admin::with('commentsCountRelation')->findOrFail($id);
$admin->commentsCount;
但它总是返回null
,这是为什么
以下针对的作品有很多
&属于
,我已经在我的其他车型上使用过,如:
//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
任何帮助都将受到高度赞赏无需使用
hasManyThrough
只需使用一些关系和
with count
方法:
$admin->posts->withCount('comments')->get()代码>
然后您可以使用以下命令访问它:$comments\u count
无需使用hasManyThrough
只需使用一些关系和with count
方法:
$admin->posts->withCount('comments')->get()代码>
然后您可以使用以下命令访问它:$comments\u count
我不明白。该应用程序有多个管理员&所有管理员都有帖子。现在我需要来自特定管理员的所有帖子&所有评论只对那些帖子有效,我描述了表结构,我在使用admin
model时需要这些评论,你能解释一下,如果没有hasManyThrough,我怎么做吗?因为我不想得到所有帖子的计数,只想从这个管理员那里得到帖子。我需要这样做(循环后)$admin->post->commentCount
如果您能给我一些代码示例或在简短的关系中进行解释,我将不胜感激:admin
hashasMany
withpost
hashasMany
withComment
我也认为您的方法没有使用即时加载,是吗?另外,你能告诉我使用你的提及方法而不是$admin->post->comments->count()
我不明白的方法有什么效率优势吗。该应用程序有多个管理员&所有管理员都有帖子。现在我需要来自特定管理员的所有帖子&所有评论只对那些帖子有效,我描述了表结构,我在使用admin
model时需要这些评论,你能解释一下,如果没有hasManyThrough,我怎么做吗?因为我不想得到所有帖子的计数,只想从这个管理员那里得到帖子。我需要这样做(循环后)$admin->post->commentCount
如果您能给我一些代码示例或在简短的关系中进行解释,我将不胜感激:admin
hashasMany
withpost
hashasMany
withComment
我也认为您的方法没有使用即时加载,是吗?另外,您能告诉我使用您的提及方法而不是$admin->post->comments->count()