Laravel 中的连接查询中的参数化分组

Parameterized grouping in join query in Laravel

我有三个 table:adminsusersmaintenances,结构如下。

admins table: (类型=1)

admin_id admin_name admin_table  theme ... 
1           A         ..
2           B         ..  


users table(类型=2):

user_id user_name
1           A
2           B
3           C


maintenances table:

maintenance_id  requester_type  requester payer_type payer
1                    2             3         2        3
1                    2             4         1        1
1                    2             1         2        1
1                    1             1         1        1

我需要获取用户详细信息和维护次数。如果请求者或付款者是该用户,则可以为该用户计算维护。

SELECT u.*, COUNT(m.maintenance_id) as maintenanceCount 
FROM users as u
LEFT JOIN maintenances as m ON ((m.requester_type=2 AND m.requester_id=u.user_id) OR (m.payer_type=2 AND m.payer_id=u.user_id))
GROUP BY user_id

使用 laravel 查询生成器,我试过:

DB::table('users as u')
   ->leftjoin('maintenances as m', function($join){
              $join->on('m.requester_type', '=', DB::raw(2))
              ->where('m.requester_id', 'u.user_id');
    })
   ->groupby('user_id')
   ->select('u.*', DB::raw('Count(m.maintenance_id) as maintenanceCount)')->get(); 

但这是错误的。如何对加入 Laravel 查询生成器的条件进行分组?有人可以帮忙吗

   DB::table('users as u')
   ->leftjoin('maintenances as m', function($join){
              $join
                  ->where(function ($on) {
                      $on->where('m.requester_type', 2)
                         ->whereRaw('m.requester_id = u.user_id');
                  })
                  ->orWhere(function ($on) {
                      $on->where('m.payer_type', 2)
                         ->whereRaw('m.payer_id = u.user_id');
                  });
    })
   ->groupby('user_id')
   ->select('u.*', DB::raw('Count(m.maintenance_id) as maintenanceCount)')->get();