下面我粘贴了 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;
最佳答案
以下是编写它的方法(但是,您可能想测试此代码)。
使用DB::raw
需要注意的事情:
DB::raw() is used to make arbitrary SQL commands which aren't parsed any further by the query builder. They therefore can create a vector for attack via SQL injection.
考虑到这一点,我在这里使用它们假设您没有将任何用户输入传递给它们来执行计数和条件查询参数。
请看一下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();
关于mysql - 如何将 mysql 查询转换为 laravel 5?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34893563/