单个Laravel中的多条件计数选择查询
我正在尝试根据不同的条件来计数票证
。我在同一模型上使用了四个不同的查询。我可以仅使用一个查询执行所有计算吗?
$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();
I am trying to count tickets
based on different where conditions . I am using four different queries on the same model. Can I execute all of the calculations using just one query?
$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();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您当然可以通过此查询解决多个查询。我们可以使用条件案例和计数。
You can of course resolve the multiple queries with this query. We can use conditional cases and count.
您可以总结有条件的条件,但在查询中需要许多原始零件:
You can sum up conditionals but will need lots of raw parts in your query:
count()
在语义上适合此任务,而sum()
可以更方便地消耗有条件的表达式,并取决于false/true结果的效果为0或1每个评估。使用selectraw()
一次或四次构建Select子句,然后first()
填充具有所需条件计数的对象。代码:( phpize demo )
输出:
While
COUNT()
is semantically appropriate for this task,SUM()
can more conveniently consume a conditional expression with the effect of summing 0 or 1 depending on the false/true result of each evaluation. UseselectRaw()
one or four times to build the SELECT clause, thenfirst()
to populate an object with the desired conditional counts.Code: (PHPize Demo)
Output: