От SQl до Laravel Query builder - PullRequest
1 голос
/ 14 марта 2019

У меня есть этот 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; 

1 Ответ

0 голосов
/ 14 марта 2019

Использовать DB :: raw ()

$users = DB::select(DB::raw("YOUR QUERY AS IT IS"));

С помощью Query Builder - вы можете попробовать что-то вроде этого ..

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

Дайте мне знать, если это поможет ..

...