模型类MyModel具有以下行为
public function behaviors() {
return [
'CTimestampBehavior' => [
'class' => 'zii.behaviors.CTimestampBehavior',
'createAttribute' => null,
'updateAttribute' => 'update_time',
'setUpdateOnCreate' => true
]
];
}
在代码中,在控制器中,我写了一些类似的东西
$model = new MyModel();
$dataReader = Yii::app()->db->createCommand()
->selectDistinct('some fields')
->from('MyModel')
->leftJoin('some table')
->where('some criteria')
->query();
while ($item = $dataReader->readObject('MyMode', $model->getAttributes())) {
**//!!! HERE item array is with model attributes, which are empty**
$items[] = $item;
}
灾难,它不起作用,项是数组,每个元素都有空的属性列表,就像没有从数据库中提取数据一样
如果我写
$dataReader = Yii::app()->db->createCommand()
->selectDistinct('some fields')
->from('MyModel')
->leftJoin('some table')
->where('some criteria')
->query();
while ($item = $dataReader->readObject('MyModel', MyModel::model()->getAttributes())) {
//!!! HERE item array is with model attributes, which hold correct data, taken from db
$items[] = $item;
}
正在工作
如果我去掉CTimestamp行为,这两种情况都有效。
如果我调试第一种情况,我会意识到,在pdo-fetchobject完成后,它会调用带有scenario="current_timestamp(("的构造函数。问题是为什么?我哪里走错路了?
如果您阅读readObject()
文档,您会发现第二个参数不是字段列表,而是构造函数参数列表。CActiveRecord
只有一个构造函数参数$scenario
。$dataReader->readObject('MyMode', $model->getAttributes())
本质上分配随机值作为场景,因为它将从$model->getAttributes()
获得第一个值。在您的情况下,您可能需要:
$item = $dataReader->readObject('MyModel', []);