RatingBehavior.php 1.11 KB
<?php
    
    namespace common\behaviors;
    
    use common\models\Articles;
    use common\modules\comment\models\CommentModel;
    use common\modules\product\models\Product;
    use yii\base\Behavior;
    use yii\base\Event;
    use yii\db\ActiveRecord;
    
    /**
     * Class RatingBehavior
     * @property CommentModel $owner
     * @package common\behaviors
     */
    class RatingBehavior extends Behavior
    {
        
        public function events()
        {
            return [
                ActiveRecord::EVENT_AFTER_UPDATE => 'afterUpdate',
            ];
        }
        
        public function afterUpdate($event)
        {
            /**
             * @var Event        $event
             * @var CommentModel $owner
             */
            $owner = $this->owner;
            if($owner->entity == Product::className() || $owner->entity == Articles::className()) {
                $entity = $owner->entity;
                $model = $entity::findOne($owner->entity_id);
                if($model != NULL) {
                    $model->recalculateRating();
                }
            }
        }
    }