Laravel where和orWhere函数

时间:2019-03-08 16:31:38

标签: mysql laravel eloquent where

我试图计算我们的运营商在一周内(每天)关闭了多少张票,我有这两个查询

    $closedWeek = Ticket::join('activity_log', 'activity_log.rel_id', '=', 'ticket.id')
                ->where([
                    ['activity_log.created_at',  '>', $fri],
                    ['activity_log.user_id', '=', $id],
                    ['activity_log.event_name', '=', 'ticket_closed'],
                    ['number', 'like', 'SD%']
                ])->count();

    $closedWeek2 = Ticket::join('activity_log', 'activity_log.rel_id', '=', 'ticket.id')
                ->where([
                    ['activity_log.created_at',  '>', $fri],
                    ['activity_log.user_id', '=', $id],
                    ['number', 'like', 'SD%'],
                    ['activity_log.event_name', '=', 'ticket_department_updated']
                ])
                ->where(function($query) {
                    $query->where('activity_log.new_value', '=', 'closed Uninvoiced')
                        ->orWhere('activity_log.new_value', '=', 'To Invoice')
                        ->orWhere('activity_log.new_value', '=', 'closed Other')
                        ->orWhere('activity_log.new_value', '=', 'closed Invoiced');
                })->count();
    $closedWeek = $closedWeek + $closedWeek2;

它们带来的数字比预期的要大一些,我认为其中一些是重复的。如何使用where(function($ query))将它们放入一个查询中,还是必须使用DB :: raw?然后,我可以计算唯一的ID

1 个答案:

答案 0 :(得分:0)

您可以将GroupBy();与id一起使用

示例:

$closedWeek = Ticket::join('activity_log', 'activity_log.rel_id', '=', 'ticket.id')
                ->where([
                    ['activity_log.created_at',  '>', $fri],
                    ['activity_log.user_id', '=', $id],
                    ['activity_log.event_name', '=', 'ticket_closed'],
                    ['number', 'like', 'SD%']
                ])
                ->groupBy('ticket.id')
                ->count();

    $closedWeek2 = Ticket::join('activity_log', 'activity_log.rel_id', '=', 'ticket.id')
                ->where([
                    ['activity_log.created_at',  '>', $fri],
                    ['activity_log.user_id', '=', $id],
                    ['number', 'like', 'SD%'],
                    ['activity_log.event_name', '=', 'ticket_department_updated']
                ])
                ->whereIn('activity_log.new_value', 
                    [   'closed Uninvoiced', 
                        'To Invoice',
                        'closed Other',
                        'closed Invoiced',
                ])
                ->groupBy('ticket.id')
                ->count();
$closedWeek = $closedWeek + $closedWeek2;

OBS:

  

在相同的地方都不需要'=',示例where('colun', '=', 'abc');可以更改为where('colun', 'abc');

请进行测试,看看是否有预期的结果。

参考文献:

How to get distinct values for non-key column fields in Laravel?