yii2yii2-advanced-appyii2-user

Yii2 Override find() to add default condition globally


I have to override the method using

namespace common\models;
use Yii;
use yii\db\ActiveQuery;

class Addfindcondition extends ActiveQuery
{

    public function init()
    {

        $this->andOnCondition([$this->modelClass::tableName() . '.branch_id' => Yii::$app->user->identity->branch_id ]);
        parent::init();
    }
}

And call the method in each model separately like this

public static function find()
{
    return new Addfindcondition(get_called_class());
}

Now I want to override the find method globally. How it is possible that I dont need to use this static method in each model


Solution

  • You can override the find() method in case of ActiveRecord models, as you need to add this for all models you should create a BaseModel say

    common\components\ActiveRecord or inside your models if you like

    <?php
    namespace common\components;
    use yii\db\ActiveRecord as BaseActiveRecord;
    
    class ActiveRecord extends BaseActiveRecord{
        public static function find() {
           return parent::find ()
            ->onCondition ( [ 'and' ,
                [ '=' , static::tableName () . '.application_id' , 1 ] ,
                [ '=' , static::tableName () . '.branch_id' , 2 ]
            ] );
        }
    }
    

    And then extend all your models where you need to add this condition to the find() method, replace yii\db\ActiveRecord to common\components\ActiveRecord for instance if I have a Product Model and I want to add the conditions to it by default I will change the model from

    <?php
    
    namespace common\models;
    
    use Yii;
    
    class Product extends yii\db\ActiveRecord {
    

    to

    <?php
    
    namespace common\models;
    
    use Yii;
    
    class Product extends common\components\ActiveRecord{