如何更改由findAll方法返回的CActiveRecord中属性的格式



我的模型中有一个属性,它以二进制格式存储在数据库中。如果属性是一个几何(多边形)对象

该对象可以被强制转换为多个字符串表示形式。那么,如何在find执行之后附加一个事件,使我只能更改返回集合上的属性呢?

我的第一个猜测是使用onAfterFind事件,但它没有像文档建议的那样调用创建元素的处理程序。我的第一次尝试是在控制器中执行以下操作。

// 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
}

这样做的正确方法是,在您的模型中有一个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方法。

最新更新