For example, a Order AR object has many OrderItem objects, the code below generates json string containing values of Order object only but not its OrderItem objects. Any easy way to generate a json string containing values of OrderItem objects also, with a proper structure? I know some frameworks can do this with one line of code, but do not know how to do this with Yii.
i just ran into this problem as wel… i was trying to save the CSort, CPaginationand and the CDbCriteria object into an cookie os i can restore the state of my CGridView. But when i encode the object for storing the data into a cookie and i decode them it’s not a CSort, CPaginationof or CDbCriteria object anymore…
The resulted json with your code contains DB schema and other infomation of the AR objects, which generates more traffic and makes parsing with javascript more difficult.
Many thanks for your great help. I am looking for something like this! I’ll modified your code to fit my need (for example, if a related object is not eagerly loaded, do not include in the retulted JSON. And, the resulted JSON is in the structure such that, we can access [font=“Courier New”]order.orderItems[0].unitPrice[/font] in JavaScript, like we can do similar things in PHP with [font=“Courier New”]$orderItems = $order->orderItems; echo $orderItems[0]->unitPrice;[/font]
I don’t think is not right to modify the library, at the most you can extend from the CJSON object and override…
If you do that, you make CJSON not able to work with other type of objects. Imagine you wish to encode other objects that do not have relations() method.
Yeah, you are right Antonio. I was thinking about this later and realized that this is true. The way that CJSON works is it exposes the properties of the object to the get_object_vars() method and encodes them into JSON. Do you think there is a way to expose related objects as properties once they are retrieved through eager loading?
Okay so here is my solution that I think is a good solution. This solution extends the CActiveRecord and overrides the getIterator() method. In each class that you extend CActiveRecord, place this block of code in your class:
/**
* @return CMapIterator the iterator for the foreach statement
*/
public function getIterator()
{
$attributes=$this->getAttributes();
$relations = array();
foreach ($this->relations() as $key => $related)
{
if ($this->hasRelated($key))
{
$relations[$key] = $this->$key;
}
}
$all = array_merge($attributes, $relations);
return new CMapIterator($all);
}
I think this may be a good solution that is really quick and it exposes the related fields as if they were properties of the object. What do you think of this Antonio? Would you change anything?