We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Phalcon include relationships in json

I've been having a look at phalcon as an alternative to a laravel project that I'm running. It's mainly a REST api. I'm trying to figure out how to include relationships in a json response for models.

For example, if I had 2 models, set up like below:

class Clients extends \Phalcon\Mvc\Model
{
    public function initialize() {
        $this->hasMany('clientid','Contacts','clientid')
    }
}

class Contacts extends \Phalcon\Mvc\Model {
    public function initialize() {
        $this->belongsTo('clientid','Clients','clientid')
    }
}

And I did a:

$clients = Client::find();
return json_encode($clients->toArray());

How would I get it to automatically include the contacts?

I need to output to be something like this:

[{ clientid:'1111', contacts:[ { contactid:111 } ] }];

Many thanks!

edited Nov '14

Hello,

Look here https://forum.phalcon.io/discussion/1437/getting-all-children-grandchildren-etc-from-model-with-hasmany-r#C13636 it'll be a bit helpful but not completely, as you want to have a resultSet => to array conversion and not a model (+submodel) => to array.

One method could be to overwrite the toArray of your Client object, and get all Contacts like this :

public function toArray()
{
    $res = parent::toArray();
    $res['contacts'] = [];
    foreach ($this->Contacts as $contact) {
       $res['contacts'][] = $contact->toArray();
    }
    return $res;
}

your code would be at the end :

$clients = Clients::find();
$result = [];
foreach ($clients as $client) {
    $result[] = $client->toArray();
}
return json_encode($result);


3.5k

Many thanks for pointing me in the right direction.