我想对一段关系进行多项计算。我可以使用 withCount 方法执行 1 并向其传递一个条件如下的闭包: $subscribedAudits = Audit::whereHas('users', function ($query) { $query->whereIn('user_id', [Auth::user()->id])->where('approved', 1); })->withCount(['users' => function($query) { $query->where('approved', 0); }])->with(['users'])->get();这会在结果上创建一个字段,该字段名为users_count批准的用户数 = 0。这是预期的结果。现在我想对用户表上的另一个字段进行计数,但我不确定如何将其用于 Eloquent 查询。我尝试了以下内容: $subscribedAudits = Audit::whereHas('users', function ($query) { $query->whereIn('user_id', [Auth::user()->id])->where('approved', 1); })->withCount(['users' => function($query) { $query->where('approved', 0); }])->withCount(['users' => function($query) { $query->where('viewed', 0); }])->with(['users'])->get();这将不起作用,因为它只能返回 1 个名为 的属性users_count。有没有办法解决这个问题而不做另一个查询?
2 回答
人到中年有点甜
TA贡献1895条经验 获得超7个赞
您可以将多个计数传递给该withCount方法并给它们一个自定义名称,如下所示:
Model::withCount([
'relationship as count_1' => function ($query) {
$query->where('active', 1);
},
'relationship as count_2' => function ($query) {
$query->where('active', 0);
}
]);
在您的情况下,它将是这样的:
$subscribedAudits = Audit::whereHas('users', function ($query) {
$query->whereIn('user_id', [Auth::user()->id])->where('approved', 1);
})->withCount([
'users as disapproved_count' => function ($query) {
$query->where('approved', 0);
},
'users as not_viewed_count' => function ($query) {
$query->where('viewed', 0);
}
])->with(['users'])->get();
- 2 回答
- 0 关注
- 92 浏览
添加回答
举报
0/150
提交
取消