Behavior and afterFind

Hi there everybody!

I have Payment model that extends ActiveRecord class and I have attached a behavior that basically divide the paid_amount attribute for 100 in the afterFind event and multiply for 100 in the beforeUpdate and beforeInsert in order to store money amount values as integers. So far so good.

I have noticed as calling the find() method in the following way cause the afterFind event not to be triggered:




Payment::find()->where(['id_invoice' => $this->id])->sum('paid_amount');



I believe this happens because of the event triggering (as explained in the guide). In this case no record is created nor populated with query results because the result is a scalar value (am I wrong?) My question is: is there a way to overcome this issue? I suppose one way could be calculating the sum using a foreach loop instead of mysql like this:




$payments = Payment::find()->where(['id_invoice' => $this->id])->all();

$sum = 0;

foreach($payments as $payment){

  $sum += $payment->paid_amount;

}

return $sum;



But I believe it is always better to delegate calculations (whenever possible) to the db instead of on the server…

Thanks in advances and cheers!

Makes sense that no "afterFind" is fired, if no record is found.

Idea, untested:




Payment::find()->where(['id_invoice' => $this->id])->sum(new Expression('paid_amount/100'));



Indeed is what I need! :lol: Thank you very much!!!