Use Yii findAll to return a model w/ all propertie

2019-08-21 15:16发布

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条回答
老娘就宠你
2楼-- · 2019-08-21 15:56

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;
    }
查看更多
登录 后发表回答