Use Yii findAll to return a model with all properties

I'm still new to Yii and wondering how to return JSON from $models = MyModel::model()->findAll(); .

Say, for example, MyModel is relevant for MyChildModels in the ONE: MANY method.

Right from the Rest example on the Yii website, I have:

 foreach ($models as $model) { $rows[] = $model->attributes; } $this->_sendResponse(200, CJSON::encode($rows), 'application/json'); 

I get all the attributes of the model, but NOT related link attributes.

Similarly, I can change the $rows line:

 $rows[] = $model->myChildModels; 

... and I get all MyChildModels attributes for each model, but not any attributes (as you would expect).

But I need a complete set - Model PLUS attributes are all MyChildModels and their attributes.

How to do it?

0
source share
1 answer

I do the same with Yii. This is how I do it.

 $models = MyModel::model()->findAll(); if ($models){ echo CJSON::encode($models); } 

I usually did not send a JSON header, but you can if you want.

 header('Content-type: application/json'); 

for related models try this.

 foreach ($models as $model) { $rows[] = $model->attributes; $rows[] = $model->related->attributes; } 
+5
source

All Articles