user filter – lastEvents

Dołącza podzbiór zdarzeń na kliencie i znajduje ostatnie zdarzenie, zaraportowane, starsze niż obecna data (przyszłe zdarzenia nie miały miejsca to tylko plany). Jeśli ostatnie zdarzenie jest starsze niż 3 miesiące ustawia alarm.

public function findLastEvent($query, $options)
{
  $query = $query->contain([
      'Events' => function($q){
                     return $q->select([
                       'id', 'company_id', 'last_visit' => 'MAX(start_date)', 
                       'alarm' => $q->newExpr()->addCase(
                        [ $q->newExpr()->lt('MAX(start_date)', 
                                     $q->func()->dateAdd('CURRENT_DATE', -3, 'MONTH')) 
                            ],
                        [1,0],
                        ['integer', 'integer']
                      )  // addCase
                 ])  // select
                ->where(['report <>' => '']) // Zaraportowane
                ->where(['start_date <=' => new \DateTime('now')])
                ->order(['start_date' => 'DESC'])
                ->group(['Events.id']);
         }]);
   return $query;
}