Yii 如何更改findAll方法返回的CActiveRecord中属性的格式?
我的模型中有一个属性,它以二进制格式存储在数据库中。 如果属性是几何(多边形)对象 此对象可以强制转换为多个字符串表示形式。 那么,如何在find执行后附加一个事件,该事件只允许我更改返回集上的属性呢 我的第一个猜测是使用onAfterFind事件,但它并没有像文档所建议的那样使用创建的元素调用处理程序。我的第一次尝试是在控制器中执行以下操作Yii 如何更改findAll方法返回的CActiveRecord中属性的格式?,yii,yii-events,Yii,Yii Events,我的模型中有一个属性,它以二进制格式存储在数据库中。 如果属性是几何(多边形)对象 此对象可以强制转换为多个字符串表示形式。 那么,如何在find执行后附加一个事件,该事件只允许我更改返回集上的属性呢 我的第一个猜测是使用onAfterFind事件,但它并没有像文档所建议的那样使用创建的元素调用处理程序。我的第一次尝试是在控制器中执行以下操作 // an activeRecord class GeoTableBinaryData extends CActiveRecord { ... // n
// an activeRecord class
GeoTableBinaryData extends CActiveRecord {
... // normal active record with a table which has a binary attribute called geom
}
$model = GeoTableBinaryData::model();
$model->onAfterFind->add(
function( CEvent $evt ){
// get the finded object to update the geom attribute on the fly here want
// a text representation in other case would transform it to XML or JSON
}
);
foreach ( $model->findAll() as $geoInfo )
{
... // output serialized geometry
}
正确的方法是,在您的模型中使用一种事后发现方法,如:
protected function afterFind()
{
$this->someAttribute = $this->methodToChangeTheAttribute($this->someAttribute);
return parent::afterFind();
}
也就是说,当您使用AR的方法时,每个找到的模型都将通过
afterFind()
并根据需要更改someAttribute
。正确的方法是,在您的模型中有一个afterFind方法,如:
protected function afterFind()
{
$this->someAttribute = $this->methodToChangeTheAttribute($this->someAttribute);
return parent::afterFind();
}
总之,当您使用AR的方法时,每个找到的模型都将通过
afterFind()
并根据需要更改someAttribute
。您还可以为不同的格式编写getter:
public function getGeoAsString()
{
// Create the string from your DB value. For example:
return implode(',', json_decode($this->geom));
}
然后可以像使用常规(只读)属性一样使用
geoAsString
。如果要使setter方法可写,还可以添加setter方法。还可以为不同格式编写getter:
public function getGeoAsString()
{
// Create the string from your DB value. For example:
return implode(',', json_decode($this->geom));
}
然后可以像使用常规(只读)属性一样使用
geoAsString
。如果您想使其可写,还可以添加setter方法。但是如果这是唯一的方法,那么如果您不能倾听Yii上的事件并做出反应,那么Yii上的事件(onAfterFind)的目的是什么?我试图将一个列表器附加到afterFind以进行此操作,但eventListener从未收到AR创建新实例的通知。Bug?您可以创建附加到afterFind()方法的行为。此外,您应该研究如何正确地附加事件处理程序,只需查看CActiveRecordBehavior以了解它是如何完成的,或者阅读文档。但是,如果这是唯一的方法,那么如果您无法侦听并做出反应,那么Yii上的事件(onAfterFind)的目的是什么?我试图将一个列表器附加到afterFind以进行此操作,但eventListener从未收到AR创建新实例的通知。Bug?您可以创建附加到afterFind()方法的行为。此外,您应该研究如何正确地附加事件处理程序,只需查看CActiveRecordBehavior以了解它是如何完成的,或者阅读文档。