Morray (model to array) is a behavior that converts an AR model to an array. It will include all the specified relations. This can be useful for API's that need to supply the data including related data, or exporting relational data as XML file.
You can use scenario's to specify the fields that need to be included and also their order.
Tested on Yii 1.1.8.
public function behaviors() { return array( 'MorrayBehavior'=>array( 'class'=>'application.behaviors.MorrayBehavior' ), ); }
//retrieve model like normal $obj = User::model()->findByPk(1); //call the toArray() method to convert the data to an array $arr = $obj->toArray();
If you use findAll(), Yii will return an array of objects, loop them to get the data:
$objects = User::model()->findAll(); $arr = array(); foreach ($objects as $obj) { $arr[] = $obj->toArray(); }
To exclude some fields (passwords, timestamps, etc) we can use scenario's: Create a new validation rule in the AR model from which you want to exclude fields, and specify the safe attributes. These are the fields that will be included. (The order of the fields are preserved in the output array.)
public function rules() { return array( array('id, first_name, last_name, username', 'safe', 'on' => 'myname'), ); }
You need to specify the scenario name when retrieving the data:
$arr = $obj->toArray(array("scenario"=>"myname"));
Note that relations should be eager loaded, for example using a scope or using 'with'.
Please report any bugs or shortcomings below.
Total 1 comment
When using toArray in a loop like so:
I get an error that I cannot redeclare loop(). I fixed it, by putting the loop function outside of toArray();
Leave a comment
Please login to leave your comment.