【问题标题】:From SQl to Laravel Query builder从 SQL 到 Laravel 查询构建器
【发布时间】:2019-08-05 12:50:06
【问题描述】:

我有这个 SQL 查询,但不知道如何在 Laravel 查询生成器中编写它

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; 

【问题讨论】:

    标签: sql laravel query-builder


    【解决方案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();
    

    如果有帮助请告诉我..

    【讨论】:

    • 虽然可能,但这会绕过很多有用的 Laravel 功能。如果可能的话,通常最好正确迁移代码以使用 Eloquent(或 Fluent,如果它与实际模型无关)。
    • @Gopal Panadi 谢谢老兄!搞定了 0 =&gt; {#957 ▼ +"state_id": "1" +"state_name": "تونس 1" +"inactifs": "3188" +"actifs": "45" +"total": "3233" } 1 =&gt; {#964 ▼ +"state_id": "2" +"state_name": "تونس 2" +"inactifs": "1365" +"actifs": "32" +"total": "1397" } ...
    • 没有问题@LaadhariAmine。仍然得到-1:D
    • 当建议使用DB::raw 时,您还应该强调SQL 注入的风险,并鼓励在查询中使用任何用户输入时使用绑定。请记住,当您提供如此简短的答案时,一些偶然发现您的答案的新手程序员会忘记他们所暴露的任何风险。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    • 2016-02-04
    • 1970-01-01
    相关资源
    最近更新 更多