假设我使用数据透视表 role_user 表有多对多关系表 user 和 roles .
role_user
user
roles
我在我的模型上使用 belongstomany 关系
belongstomany
如何制作一个雄辩的查询来计算有多少用户有角色 admin 和 staff
admin
staff
解决了 .
将此添加到 Role.php 型号
Role.php
public function userCount() { return $this->belongsToMany(Role::class) ->selectRaw('count(role_user.user_id) as total_user') ->groupBy('role_id'); }
还有这个
public function getUserCountAttribute() { if ( ! array_key_exists('userCount', $this->relations)) $this->load('customerCount'); $related = $this->getRelation('userCount')->first(); return ($related) ? $related->total_user : 0; }
在那之后,做一个雄辩的查询......
$roleUsers = Role::with('userCount')->orderBy('id', 'asc')->get();
1 回答
解决了 .
将此添加到
Role.php
型号还有这个
在那之后,做一个雄辩的查询......