2016-01-20 100 views
0

下面我粘贴了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; 
+0

为什么要将其转换为Laravel的方案?只需创建一个视图,并与口才...... –

+0

我的项目在laravel我的工作进行查询,和我在MySQL的解决方案,但我没有对自己在使用laravel情况下任何想法。这就是为什么。\ –

+0

好吧,那么有道理。转换它祝你好运!我相信给出的答案可以满足你的需求,你试过了吗? –

回答

1

以下是如何编写它(您可能想要测试此代码,但是)。

一些需要注意的有关使用DB::raw

DB ::原始()是用来做未通过查询器解析任何进一步的任意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();