使用Yii中的findAll返回一个模型瓦特/所有属性 [英] Use Yii findAll to return a model w/ all properties
问题描述
我还是新来的Yii,不知道如何从 $模式=为MyModel ::模型()返回JSON - >的findAll();
I am still new to Yii and wondering how to return JSON from the $models = MyModel::model()->findAll();
.
说,例如为MyModel
在一个ONE的关系为 MyChildModels
:很多时尚
Say for example MyModel
has a relation for MyChildModels
in a ONE:MANY fashion.
直接从在Yii的网站我有休息的例子:
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;
...和我得到的所有的 myChildModels
属性每个模型,但没有任何属性(如我期望的那样)。
...and I get all of the myChildModels
attributes for each model, but not any attributes (as I would expect).
但我要的是完整的套件 - 型号
属性加上所有的 myChildModels
及其属性。
But what I want is the full suite - the Model
attributes PLUS all of the myChildModels
and their attributes.
我如何做到这一点?
推荐答案
我做同样的事情用Yii的。下面是我如何做到这一点。
I do the same thing with Yii. Here is how I do it.
$models = MyModel::model()->findAll();
if ($models){
echo CJSON::encode($models);
}
我不正常发送一个JSON头,但你可以,如果你想要的。
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;
}
这篇关于使用Yii中的findAll返回一个模型瓦特/所有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!