Yii2 覆盖 find() 以全局添加默认条件 [英] Yii2 Override find() to add default condition globally
问题描述
我必须使用
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());
}
现在我想全局覆盖 find 方法.我怎么可能不需要在每个模型中使用这个静态方法
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
推荐答案
您可以在 ActiveRecord
模型的情况下覆盖 find()
方法,因为您需要添加这对于所有模型你应该创建一个 BaseModel 说
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
或在您的模型中(如果您愿意)
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 ]
] );
}
}
然后扩展你所有需要在find()
方法中添加这个条件的模型,将yii\db\ActiveRecord
替换为common\components\ActiveRecord
例如,如果我有一个 Product
模型并且我想默认添加条件,我将从
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 {
到
<?php
namespace common\models;
use Yii;
class Product extends common\components\ActiveRecord{
这篇关于Yii2 覆盖 find() 以全局添加默认条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!