我有Yii应用程序和两个具有相同结构的表tbl和tbl_history:
现在想要创建模型,因此它将在调用模型时通过我发送的参数选择表.例如:
MyModel::model('tbl')->find(); //and MyModel::model('tbl_history')->find();
在Yii论坛中找到related article解决方案.做了相同的更改,最后在MyModel中得到了这个:
private $tableName = 'tbl'; // <=default value private static $_models=array(); private $_md; public static function model($tableName = false,$className=__CLASS__) { if($tableName === null) $className=null; // this string will save internal CActiveRecord functionality if(!$tableName) return parent::model($className); if(isset(self::$_models[$tableName.$className])) return self::$_models[$tableName.$className]; else { $model=self::$_models[$tableName.$className]=new $className(null); $model->tableName = $tableName; $model->_md=new CActiveRecordMetaData($model); $model->attachBehaviors($model->behaviors()); return $model; } }
现在当我做:
echo MyModel::model('tbl_history')->tableName(); // Output: tbl_history
它返回正确的值,但是:
MyModel::model('tbl_history')->find();
仍然返回tbl的值.
添加:
public function __construct($id=null,$scenario=null){ var_dump($id); echo '<br/>'; parent::__construct($scenario); }
得到了:
string(tbl_history) string(tbl_history) NULL
这意味着Yii从其他地方调用模型,但不知道从哪里以及如何防止它.
看起来需要重写CActiveRecord :: getMetaData()方法才能实现您的目标.
原文链接:https://www.f2er.com/php/132884.html<?PHP class TestActiveRecord extends CActiveRecord { private $tableName = 'tbl'; // <=default value private static $_models=array(); private $_md; public function __construct($scenario='insert',$tableName = null) { if($this->tableName === 'tbl' && $tableName !== null) $this->tableName = $tableName; parent::__construct($scenario); } public static function model($tableName = false,$className=__CLASS__) { if($tableName === null) $className=null; // this string will save internal CActiveRecord functionality if(!$tableName) return parent::model($className); if(isset(self::$_models[$tableName.$className])) return self::$_models[$tableName.$className]; else { $model=self::$_models[$tableName.$className]=new $className(null); $model->tableName = $tableName; $model->_md=new CActiveRecordMetaData($model); $model->attachBehaviors($model->behaviors()); return $model; } } public function tableName() { return $this->tableName; } /** * Returns the Meta-data for this AR * @return CActiveRecordMetaData the Meta for this AR class. */ public function getMetaData() { if($this->_md!==null) return $this->_md; else return $this->_md=static::model($this->tableName())->_md; } public function refreshMetaData() { $finder=static::model($this->tableName()); $finder->_md=new CActiveRecordMetaData($finder); if($this!==$finder) $this->_md=$finder->_md; } }