Laravel中的反向关系查找

时间:2016-07-20 09:41:14

标签: sql laravel eloquent

如何在Eloquent中执行以下查询?

SELECT count(*) as total, age
FROM user
JOIN role ON user.role_id = role.id
WHERE role.name = 'maintenance'
GROUP BY age

(其中'年龄'是用户)

1 个答案:

答案 0 :(得分:1)

未测试:

$total = App\User::whereHas('roles', function ($query) {
    $query->where('name', 'maintenance');
})->groupBy('age')->count();