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

时间:2018-03-12 06:11:26

标签: laravel left-join laravel-5.3

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

admins table:(type = 1)

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


users表(type = 2):

user_id user_name
1           A
2           B
3           C


  maintenances表:

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查询构建器的条件进行分组?有人可以帮忙吗

1 个答案:

答案 0 :(得分:1)

   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();