How to change the format of an attribute in a CActiveRecord returned by a findAll method?

StackOverflow https://stackoverflow.com/questions/16798764

  •  30-05-2022
  •  | 
  •  

I have an attribute in my model that is stored in binary format inside database. In case the attribute is a geometric( polygon ) object.

This object can be casted to several string representations. So how can I attach an event after a find execution that allows me to change the attribute on returned set only?

My first guess was to use the onAfterFind event but it is not calling the handler with the created element as documentation suggests. My first attempt was the following in the controller.

// 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
}
有帮助吗?

解决方案 2

You can also write getters for your different formats:

public function getGeoAsString()
{
    // Create the string from your DB value. For example:
    return implode(',', json_decode($this->geom));
}

Then you can use the geoAsString like a regular (read-only) attribute. You can also add a setter method, if you want to make it writeable.

其他提示

The correct way of doing this, is that in your model have a afterFind method like:

protected function afterFind()
{
     $this->someAttribute = $this->methodToChangeTheAttribute($this->someAttribute);
     return parent::afterFind();
}

and that's all, when you will use AR's methods, every found model will pass through afterFind() and alter the someAttribute as you want.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top