[size="5"]After looking at the comments in the EJsonBehavior extension page and according to my needs, I added the following features to the extension:
[/size]
-
It includes only relations specified by (with) in the model, which are loaded by Eager Method.
-
It gives you the choice to return an array instead of JSON encoded string that is useful in case of (findAll) query.
This is EJsonBehavior Class:
class EJsonBehavior extends CBehavior{
private $owner;
private $relations;
public function toJSON($encode = true){
$this->owner = $this->getOwner();
if (is_subclass_of($this->owner,'CActiveRecord')){
$attributes = $this->owner->getAttributes();
$this->relations= $this->getRelated();
foreach($this->relations as $key => $value)
{
$attributes[$key] = $value;
}
if($encode)
return CJSON::encode($attributes);
else
return $attributes;
}
return false;
}
private function getRelated()
{
$related = array();
$obj = null;
$md=$this->owner->getMetaData();
foreach($md->relations as $name=>$relation){
if($this->owner->hasRelated($name)){
$obj = $this->owner->getRelated($name);
$related[$name] = $obj instanceof CActiveRecord ? $obj->getAttributes() : $obj;
}
}
return $related;
}
}
And this example shows you how to use it in (findAll) context:
$devices = Device::model()->with('position')->findAll();
$json = array();
foreach($devices as $device){
$json[] = $device->toJSON(false, false);
}
header('Content-type: application/json');
echo CJSON::encode($json);
Yii::app()->end();