题
我如何通过所有关系返回对象(ANS子对象关系?)。现在,我使用Ejsonbehavior,但它仅返回第一级关系,而不返回相关的对象。我的源代码:
$order = Order::model()->findByPk($_GET['id']);
echo $order->toJSON();
Yii::app()->end();
解决方案
急切的加载方法与主AR实例一起检索相关的AR实例。这是通过将WAST()方法与AR中的一种发现或发现方法之一一起完成的。例如,
$posts=Post::model()->with('author')->findAll();
以上代码将返回一系列后实例。与懒惰的方法不同,在访问该属性之前,每个帖子实例中的作者属性已经在相关的用户实例中填充。急切的加载方法没有为每篇文章执行加入查询,而是将所有帖子与他们的作者一起回到一个联接查询中!
我们可以在使用()方法中指定多个关系名称,而急切的加载方法将把它们全部带回去。例如,以下代码将把帖子与其作者和类别融合在一起:
$posts=Post::model()->with('author','categories')->findAll();
我们还可以进行嵌套的急切加载。我们没有一个关系名称列表,而是将关系名称的层次表示为with()方法,如以下方式,
$posts=Post::model()->with(
'author.profile',
'author.posts',
'categories')->findAll();
上面的示例将把所有帖子与作者和类别一起恢复。它还将带回每个作者的个人资料和帖子。
急切的加载也可以通过指定CDBCRITERIA ::带有属性,如以下内容来执行:
$criteria=new CDbCriteria;
$criteria->with=array(
'author.profile',
'author.posts',
'categories',
);
$posts=Post::model()->findAll($criteria);
或者
$posts=Post::model()->findAll(array(
'with'=>array(
'author.profile',
'author.posts',
'categories',
)
);
其他提示
我找到了解决方案。您可以使用$ row->属性来创建数据
$magazines = Magazines::model()->with('articles')->findAll();
$arr = array();
$i = 0;
foreach($magazines as $mag)
{
$arr[$i] = $mag->attributes;
$arr[$i]['articles']=array();
$j=0;
foreach($mag->articles as $article){
$arr[$i]['articles'][$j]=$article->attributes;
$j++;
}
$i++;
}
print CJSON::encode(array(
'code' => 1001,
'magazines' => $arr,
));
这是我经过长时间搜索以满足此要求的最佳代码。这会像 魅力.
protected function renderJson($o) {
//header('Content-type: application/json');
// if it's an array, call getAttributesDeep for each record
if (is_array($o)) {
$data = array();
foreach ($o as $record) {
array_push($data, $this->getAttributes($record));
}
echo CJSON::encode($data);
} else {
// otherwise just do it on the passed-in object
echo CJSON::encode($this->getAttributes($o));
}
// this just prevents any other Yii code from being output
foreach (Yii::app()->log->routes as $route) {
if ($route instanceof CWebLogRoute) {
$route->enabled = false; // disable any weblogroutes
}
}
Yii::app()->end();
}
protected function getAttributes($o) {
// get the attributes and relations
$data = $o->attributes;
$relations = $o->relations();
foreach (array_keys($relations) as $r) {
// for each relation, if it has the data and it isn't nul/
if ($o->hasRelated($r) && $o->getRelated($r) != null) {
// add this to the attributes structure, recursively calling
// this function to get any of the child's relations
$data[$r] = $this->getAttributes($o->getRelated($r));
}
}
return $data;
}
不隶属于 StackOverflow