carjson

Convert model and its relations to a JSON String
4 followers

To develop this extension I started from ejsonbehavior. That extension wasn't fitting my own requirements so I just developed a new and fresh one!

Requirements

Was developed using Yii 1.1.4

Install

Extracxt the json directory to your protected/extensions/ directory

Usage

The first parameter can be a single model or an array of models. The other two parameters has to be array.

echo $json->toJSON( mixed $model, array $relations, array $attributes);
Yii::import('application.extensions.json.CArJSON');
$users = User::model()->findAll($criteria);
 
$json = new CArJSON();
// Define which relations do you want to load
$relations = array('posts', 'comments', 'votes');
// Define which attributes, foreach relations do you want to load
// root denote attributes for the main model
$attributes = array(
    'root' => array('id', 'username', 'email', 'first_name', 'last_name'),
        'posts' => array( 'id', 'author_id', 'content' ),
    'comments' => array( 'id', 'author_id', 'content' ),
    'votes' => null, // This will load all attributes
);
echo $json->toJSON($users, $relations, $attributes);

Resources

Total 2 comments

#7108 report it
bonnie at 2012/02/23 09:51pm
Thanks StErMi

Hi, StErMi I want a way to pass the data of the model from json to javascript where I have list list with the item_name from the item model. The same as your example but wants to pass the json to javascript. Thanks.

#2352 report it
mdomba at 2010/12/16 05:43am
note

The link for the project page is wrong - http://www.yiiframework/

Leave a comment

Please to leave your comment.

Create extension