raj*_*766 5 yii2 yii2-user yii2-advanced-app
我必须使用
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();
}
}
Run Code Online (Sandbox Code Playgroud)
并像这样分别调用每个模型中的方法
public static function find()
{
return new Addfindcondition(get_called_class());
}
Run Code Online (Sandbox Code Playgroud)
现在我想全局覆盖 find 方法。我怎么可能不需要在每个模型中使用这个静态方法
您可以find()在ActiveRecord模型的情况下覆盖该方法,因为您需要为所有模型添加此方法,您应该创建一个 BaseModel 说
common\components\ActiveRecord 或在您的模型中,如果您愿意
<?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 ]
] );
}
}
Run Code Online (Sandbox Code Playgroud)
然后再扩展所有的车型,你需要这个条件添加到find()方法,取代yii\db\ActiveRecord以common\components\ActiveRecord例如,如果我有一个Product模式,我想用默认的条件添加到它,我会改变从模型
<?php
namespace common\models;
use Yii;
class Product extends yii\db\ActiveRecord {
Run Code Online (Sandbox Code Playgroud)
到
<?php
namespace common\models;
use Yii;
class Product extends common\components\ActiveRecord{
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1618 次 |
| 最近记录: |