我有这个数据库结构
table tools table details
----------- -------------
id * id *
name balance_shoot
tool_id
我需要计算在tools
中具有小于或等于零(危险)且大于零(保存)的balance_shoot的tool_details
的计数。类似的东西:
[
danger_count => 0,
save_count => 5
];
我已经实现了这个目标:
public function index(Request $request){
$trans_date = date('Y-m-d');
$tools = Tool::select('id')
->whereHas(
'details' , function ($query) use ($trans_date){
$query->where('trans_date', $trans_date );
}
)
/*->with([
'details' => function ($query) use ($trans_date){
$query->where('trans_date', $trans_date );
}
])*/
->withCount([
'details as danger' => function ($query) use ($trans_date){
$query->where('trans_date', $trans_date )->where('balance_shoot', '<=', 0 );
},
'details as save' => function ($query) use ($trans_date){
$query->where('trans_date', $trans_date )
->where('balance_shoot', '>', 0 );
},
]);
return $tools->get();
}
它会回复:
"tools": [
{
"id": 101,
"danger_count": "0",
"save_count": "1"
},
{
"id": 102,
"danger_count": "0",
"save_count": "1"
}
];
如何才能获得该数据结构,但只返回一个结果?
答案 0 :(得分:1)
SQL查询
select count(*) total, sum(case when balance_shoot < '0' then 1 else 0 end) danger, sum(case when balance_shoot > '0' then 1 else 0 end) safe from tool_dtl group by tool_id
在Laravel你可以尝试这个
<?php
$toolDtl = Detail::select(
array(
DB::raw('COUNT(*) as total'),
DB::raw("SUM(CASE
WHEN balance_shoot < '0' THEN 1 ELSE 0 END) AS danger"),
DB::raw("SUM(CASE
WHEN balance_shoot > '0' THEN 1 ELSE 0 END) AS save")
)
)
->groupBy('tool_id')
->orderBy('id', 'asc')->get();
?>