Let's say I have table user
and roles
with many to many relationships using pivot table role_user
table.
I'm using belongstomany
relationships on my model
How do I make an eloquent query to count how many user has role admin
and staff
solved.
add this to Role.php
model
public function userCount() {
return $this->belongsToMany(Role::class)
->selectRaw('count(role_user.user_id) as total_user')
->groupBy('role_id');
}
and this
public function getUserCountAttribute()
{
if ( ! array_key_exists('userCount', $this->relations)) $this->load('customerCount');
$related = $this->getRelation('userCount')->first();
return ($related) ? $related->total_user : 0;
}
after that, to make an eloquent query...
$roleUsers = Role::with('userCount')->orderBy('id', 'asc')->get();
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments