Use Yii findAll to return a model w/ all properties

為{幸葍}努か 提交于 2020-01-07 02:24:40

问题


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

Say for example MyModel has a relation for MyChildModels in a ONE:MANY fashion.

Straight from the Rest example on the Yii site I have:

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

$this->_sendResponse(200, CJSON::encode($rows), 'application/json');

I get all of the model's attributes but NOT the joined relation attributes.

Similarly, I can change the $rows line to be:

$rows[] = $model->myChildModels;

...and I get all of the myChildModels attributes for each model, but not any attributes (as I would expect).

But what I want is the full suite - the Model attributes PLUS all of the myChildModels and their attributes.

How do I accomplish this?


回答1:


I do the same thing with Yii. Here is how I do it.

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

I don't normally sent 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;
    }


来源:https://stackoverflow.com/questions/10184572/use-yii-findall-to-return-a-model-w-all-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!