如何根据laravel中不同的where条件进行计数?
How to take count based on different where conditions in laravel?
我正在尝试根据不同的 where 条件计算 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();
您可以总结条件,但在您的查询中需要大量原始部分:
$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;
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();
您当然可以使用此查询解决多个查询。我们可以使用条件案例并计数。
我正在尝试根据不同的 where 条件计算 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();
您可以总结条件,但在您的查询中需要大量原始部分:
$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;
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();
您当然可以使用此查询解决多个查询。我们可以使用条件案例并计数。