如何将mysql查询转换为laravel 5?

时间:2016-01-20 07:06:34

标签: mysql laravel-5

下面我已经粘贴了mysql查询。请帮我把这个问题转换成laravel 5.

select
t.username,
sum(case when t.status_id = 1 then t.count else 0 end) as status_1,
sum(case when t.status_id = 0 then t.count else 0 end) as status_0,
sum(case when t.status_id = 0 and t.status_desc = 2 then t.count else 0 end)
         as status_0_2,
sum(case when t.status_id = 0 and t.status_desc = 3 then t.count else 0 end)
as status_0_3
from (
select username, status_id, status_desc, count(status_desc) as count
from log
group by username, status_id, status_desc
) as t
group by t.username;

1 个答案:

答案 0 :(得分:1)

以下是编写它的方法(但是,您可能希望测试此代码)。

关于使用DB::raw的注意事项:

  

DB :: raw()用于创建任意SQL命令,查询构建器不再对其进行任何解析。因此,他们可以通过SQL注入创建一个攻击媒介。

考虑到这一点,我在这里使用它们假设您没有将任何用户输入传递给它们以便进行计数和条件查询参数。

请查看Laravel Documentation以获取有关查询构建器如何工作的更多信息。大多数人都不会总是很友善地为您撰写查询。

// compile the sql for the select query
$selectRaw = \DB::table('log')->select([
    'username', 
    'status_id', 
    'status_desc', 
    \DB::raw('count(status_desc) as count')
])->groupBy('username', 'status_id', 'status_desc')->toSql();

// create and execute the full query
$result = \DB::table(\DB::raw("({$selectRaw}) as t"))->select([
    't.username', 
    \DB::raw('sum(case when t.status_id = 1 then t.count else 0 end) as status_1'),
    \DB::raw('sum(case when t.status_id = 0 then t.count else 0 end) as status_0'),
    \DB::raw('sum(case when t.status_id = 0 and t.status_desc = 2 then t.count else 0 end) as status_0_2'),
    \DB::raw('sum(case when t.status_id = 0 and t.status_desc = 3 then t.count else 0 end) as status_0_3'),
])->groupBy('t.username')->get();