Yii2 Override find() to add default condition globally

眉间皱痕 提交于 2019-12-21 19:44:37

问题


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


回答1:


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{


来源:https://stackoverflow.com/questions/49317648/yii2-override-find-to-add-default-condition-globally

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!