我如何计算用户的角色数量?
当我尝试这个时:
User::with('roles')->count();
它只计算用户数。
我需要的是返回每个用户的角色数量。例如:
[
{
"id": 2,
"name": "user",
"roles": 2
},
{
"id": 3,
"name": "user",
"roles": 1
}
]
答案 0 :(得分:1)
答案 1 :(得分:0)
如果您已拥有$user
对象,则可以执行以下操作:
$rolecount = $user->roles()->count();
或者,如果您正在使用预先加载,则可以删除(
&角色)
$rolecount = $user->roles->count();