我有这个SQL查询,但不知道如何在Laravel Query Builder中编写它
select state_id, state_name, sum(inactifs) as inactifs, sum(actifs) as actifs,
sum(inactifs) + sum(actifs) as total
from
(
select distinct s.id as state_id, s.name as state_name, u.id as user_id,
case when uga.id is null then 1 else 0 end as inactifs,
case when uga.id is null then 0 else 1 end as actifs
from users u
inner join states s on u.state_id = s.id
left join user_group_affiliations uga on uga.user_id = u.id
and (uga.active = 1 and (uga.start_date is null or uga.start_date <= now()) and (uga.end_date is null or uga.end_date >= now()))
) quer group by state_id;
答案 0 :(得分:-1)
使用DB :: raw()
$users = DB::select(DB::raw("YOUR QUERY AS IT IS"));
使用查询生成器-您可以尝试类似的操作。
DB::query()->fromSub(function($main_query){
$main_query->from('users')
->select(
DB::raw('distinct s.id as state_id, s.name as state_name, u.id as user_id,
case when uga.id is null then 1 else 0 end as inactifs,
case when uga.id is null then 0 else 1 end as actifs
')
)
->join('states as s', 'u.state_id', '=', 's.id')
->leftJoin('user_group_affiliations as uga', 'uga.user_id', '=', 'u.id')
->where('uga.active', 1)
->where(function($query){
return $query->whereNull('uga.start_date')
->orWhere('uga.start_date' '<=' date_create())
})
->where(function($query){
return $query->whereNull('uga.end_date')
->orWhere('uga.end_date' '>=' date_create())
})->groupBy('u.state_id') }, "quer")->get();
让我知道是否有帮助。