jsonyiiyii-relations

Yii JSON with relations


How I can return object with all relations(ans sub objects relations?). Now I use EJsonBehavior but it returns only first level relations, not sub related objects. My source code:

    $order = Order::model()->findByPk($_GET['id']);
    echo $order->toJSON();
    Yii::app()->end();

Solution

  • The eager loading approach retrieves the related AR instances together with the main AR instance(s). This is accomplished by using the with() method together with one of the find or findAll methods in AR. For example,

    $posts=Post::model()->with('author')->findAll();
    

    The above code will return an array of Post instances. Unlike the lazy approach, the author property in each Post instance is already populated with the related User instance before we access the property. Instead of executing a join query for each post, the eager loading approach brings back all posts together with their authors in a single join query!

    We can specify multiple relationship names in the with() method and the eager loading approach will bring them back all in one shot. For example, the following code will bring back posts together with their authors and categories:

    $posts=Post::model()->with('author','categories')->findAll();
    

    We can also do nested eager loading. Instead of a list of relationship names, we pass in a hierarchical representation of relationship names to the with() method, like the following,

    $posts=Post::model()->with(
        'author.profile',
        'author.posts',
        'categories')->findAll();
    

    The above example will bring back all posts together with their author and categories. It will also bring back each author's profile and posts.

    Eager loading may also be executed by specifying the CDbCriteria::with property, like the following:

    $criteria=new CDbCriteria;
    $criteria->with=array(
        'author.profile',
        'author.posts',
        'categories',
    );
    $posts=Post::model()->findAll($criteria);
    

    or

    $posts=Post::model()->findAll(array(
        'with'=>array(
            'author.profile',
            'author.posts',
            'categories',
        )
    );