繁体   English   中英

如何在laravel中选择具有差异条件的计数

[英]how to select count with a difference condition in laravel

我有这个数据库结构

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"
    }
 ];

我怎样才能获得该数据结构,但在一个单一的结果返回?

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();
?>

我们可以使用条件SUM直接计数

Detail::select([
        DB::raw('COUNT(*) as total'),
        DB::raw("SUM(balance_shoot < '0') AS danger"),
        DB::raw("SUM(balance_shoot > '0') AS save")
])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM