質問
すべての関係でオブジェクトを返す方法(ANSサブオブジェクト関係?)。今、私はejsonbehaviorを使用しますが、サブ関連オブジェクトではなく、最初のレベルの関係のみを返します。私のソースコード:
$order = Order::model()->findByPk($_GET['id']);
echo $order->toJSON();
Yii::app()->end();
解決
熱心なロードアプローチは、関連するARインスタンスとメインARインスタンスを取得します。これは、with()メソッドを使用して、ARの発見またはFindallメソッドの1つを使用することで実現されます。例えば、
$posts=Post::model()->with('author')->findAll();
上記のコードは、さまざまな投稿インスタンスを返します。怠zyなアプローチとは異なり、各Postインスタンスの著者プロパティには、プロパティにアクセスする前に、関連するユーザーインスタンスが既に入力されています。各投稿の参加クエリを実行する代わりに、熱心なロードアプローチは、すべての投稿を著者と一緒に1回のJoinクエリに戻します!
with()メソッドで複数の関係名を指定でき、熱心な読み込みアプローチはそれらをすべて1発のショットに戻すことができます。たとえば、次のコードでは、著者やカテゴリとともに投稿を戻します。
$posts=Post::model()->with('author','categories')->findAll();
ネストされた熱心な負荷も行うこともできます。関係名のリストの代わりに、次のように、with()メソッドに関係名の階層表現を渡します。
$posts=Post::model()->with(
'author.profile',
'author.posts',
'categories')->findAll();
上記の例では、すべての投稿を著者やカテゴリと一緒に戻します。また、各著者のプロフィールと投稿を取り戻します。
以下のように、cdbcriteria ::を使用してcdbcritiaria ::を指定することにより、熱心な読み込みを実行できます。
$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-> attributesを使用してデータを作成できます
$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;
}