C
C
cat_crash2017-07-21 17:59:51
Yii
cat_crash, 2017-07-21 17:59:51

Yii2: How to add a filter to AR through behavior?

I want to make a model behavior that would itself add a filter to all SQL queries based on an authorized user (select only those records in which owner_id = current user ID)
As I understand it, the current AR can be accessed through the event: ActiveRecord::EVENT_INIT but I’ll never know how to add condition like ->andWhere(['user_id'=>Yii::$app->user->id])
Variant

public function events()
    {
        return [
            ActiveRecord::EVENT_INIT => 'afterInit',
        ];
    }
 public function afterInit($event)
    {
        $this->owner->andWhere(["owner_id" => Yii::$app->user->identity->{$this->attribute}]);

    }

throws an error Exception yii\base\UnknownMethodException

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Timofeev, 2017-07-24
@webinar

Apparently your model is inherited from activeRecords or even from Model, and the andWhere method is a method of the activeQuery class, so everything gives you right.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question