Serialization of ActiveRecord objects for AJAX

Hello,

I am trying to do some data fetching via AJAX - process the request, do a select from multiple tables (for which I created AR classes) via Criteria, model()->findAll()… and return the results as AJAX reply.

However, when I looked at resulting objects, they seemed too large (containing all metadata and stuff).

Is there any way to automatically serialize AR object into some form that could easily be transferred as a JSON object, containing only the important data (column values)?

Why don’t you pass only columns values (in arrays) then, if you need only this data?

@whitewash - http://www.yiiframework.com/doc/api/1.1/CActiveRecord#getAttributes-detail

Twisted1919: thanks, that’s almost it, for simple queries it will be surely enough.

What if I want to do the same thing, but the query is more complex (one or more joins using Criteria->with(object.relation0) etc…). I’ve noticed that it does not return related objects

Of course it doesn’t, but you can make it to do so, like:




//get the attributes for the main model, say post : 

$post = Post::model()->findByPk(1);

$attrs = $post->getAttributes();


//suppose this is a related model(well, many actually)

if(!empty($post->comments)){

   foreach($post->comments AS $comment){

      $attrs = $comment->getAttributes();

   }

}

//and for a single related model

$attrs = $post->author->getAttributes();



Simple eh ?:)