Answer the question
In order to leave comments, you need to log in
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}]);
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question