hello,
i've got a method quite heavy in code, but working ;-)
here is a list of relations attached in my model (it's a member data)
/**
* Merge array
*
* @param string $key key
* @param array $in in
* @param array $add add
*
* @return array
*/
protected function mergeArray($key, array $in, array $add)
{
return array_merge($in, $add);
}
/**
* Add child
*
* @param string $key key
* @param array $in in
* @param array $add add
*
* @return array
*/
protected function addChild($key, array $in, array $add)
{
$in[$key] = $add;
return $in;
}
/**
* Add children
*
* @param string $key key
* @param array $in in
* @param object $objects object
* @param array $arrayKey arrayKey
*
* @return array
*/
protected function addChildren($key, array $in, $objects, $arrayKey = null)
{
$in[$key] = array();
foreach ($objects as $object) {
if ($arrayKey) {
$in[$key][$object->$arrayKey] = $object->toArray();
} else {
$in[$key][] = $object->toArray();
}
}
return $in;
}
/**
* Model object to json
*
* @param array $params params
*
* @return array
*/
public function toJson(array $params = [])
{
$modelObject = $this->toArray();
foreach (static::$toJsonRelations as $related => $relation) {
$modelRelated = $this->getRelated(\Phalcon\Text::camelize($related));
if ($modelRelated) {
$modelObject = $this->$relation($related, $modelObject, $modelRelated->toArray());
}
}
$refClass = new \ReflectionClass($this);
return [
strtolower($refClass->getShortName()) => $modelObject
];
}
and initialize your model with this "relations data" :
/**
* Relation types
*
* @var array
*/
public static $toJsonRelations = [
'part' => 'addChildren',
'product' => 'addChildren',
'order' => 'addChildren', // can be mergeArray | addChild | addChildren depending on the relation ( 1<->1 | N->1 | 1->N)
];
when you'll execute
$customer = Customer::findFirst($id);
echo json_encode($customer->toJson());
you'll have all data you want attached