laravel中如何根据不同的where条件进行计数?

问题描述 投票:0回答:3

我正在尝试根据不同的条件来计算

tickets
。为此,我使用四个不同的查询但相同的模型。我可以在一次查询中完成此操作吗?

        $openTickets = Ticket::where('status',1)->count();
        $pending = Ticket::where('status',2)->count();
        $unAssigned = Ticket::where('agent_id',null)->count();
        $unResolved = Ticket::whereNotIn('status',[3,4])->count();
laravel eloquent laravel-9
3个回答
3
投票
Ticket::selectRaw('COUNT(CASE WHEN status = 1 THEN 1 END) AS open_tickets')
      ->selectRaw('COUNT(CASE WHEN status = 2 THEN 1 END) AS pending_tickets')
      ->selectRaw('COUNT(CASE WHEN agent_id IS NULL THEN 1 END) AS unassigned_tickets')
      ->selectRaw('COUNT(CASE WHEN status NOT IN (3,4) THEN 1 END) AS unresolved_tickets')
      ->first();

您当然可以用这个查询来解决多个查询。我们可以使用条件情况并进行计数。


2
投票

您可以总结条件,但在查询中需要大量原始部分:

$result = DB::table('tickets')->whereIn('status', [1,2])->orWhereNull('agent_id')->orWhereNotIn('status', [3,4]) // This is to filter out the things we don't care about
->select([
   DB::raw('SUM(IF(status = 1, 1,0)) as countOpen'),
   DB::raw('SUM(IF(status = 2, 1,0)) as countPending'),
   DB::raw('SUM(IF(agent_id IS NULL, 1,0)) as countUnassigned'),
   DB::raw('SUM(IF(status NOT IN (3,4), 1,0)) as countUnresolved'),
])->first()
$openTickets = $result->countOpen;
$pending = $result->countPending;
$unAssigned = $result->countUnassigned;
$unResolved = $result->countUnresolved;

0
投票

虽然

COUNT()
在语义上适合此任务,但
SUM()
可以更方便地使用条件表达式,其效果是根据每个评估的假/真结果求和 0 或 1。使用
selectRaw()
一到四次构建 SELECT 子句,然后使用
first()
使用所需的条件计数填充对象。

代码:(PHPize演示

var_export(
    DB::table('tickets')
    ->selectRaw("SUM(status = 1) open")
    ->selectRaw("SUM(status = 2) pending")
    ->selectRaw("SUM(agent_id IS NULL) unassigned")
    ->selectRaw("SUM(status NOT IN (3,4)) unresolved")
    ->first()
);

输出:

(object) array(
   'open' => '2',
   'pending' => '3',
   'unassigned' => '2',
   'unresolved' => '6',
)
© www.soinside.com 2019 - 2024. All rights reserved.