pun*_*k73 0 php laravel eloquent
我有这个数据库结构
table tools table details
----------- -------------
id * id *
name balance_shoot
tool_id
Run Code Online (Sandbox Code Playgroud)
我需要计算toolsBalance_shoottool_details小于或等于零(危险)和大于零(保存)的数量。就像是 :
[
danger_count => 0,
save_count => 5
];
Run Code Online (Sandbox Code Playgroud)
我已经实现了这一点:
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();
}
Run Code Online (Sandbox Code Playgroud)
它返回这个:
"tools": [
{
"id": 101,
"danger_count": "0",
"save_count": "1"
},
{
"id": 102,
"danger_count": "0",
"save_count": "1"
}
];
Run Code Online (Sandbox Code Playgroud)
我怎样才能获得该数据结构,但在一个结果中返回?
小智 7
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
Run Code Online (Sandbox Code Playgroud)
在 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();
?>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9528 次 |
| 最近记录: |