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

Automatically hydrating nested models

Hi all,

Say I have a set of models like this:

  • Pages
  • Authors
  • Media
  • Media Type

Now, say if it's structured something like:

  • Pages
    • Author [has one]
    • Media [has many]
      • Media Type [has one]

Is there a nice easy way that I can do something like this?

  <?= json_encode ($pages::findFirst(2)) ?>

And have it output a piece of JSON like this:

{
  .... // whatever data is in the 'pages' table
  author: {
    // whatever data is in the 'author' table
  },
  media: [
    {
      // whatever data is in the media table
      mediatype: {
         // whatever data is in the media type table
      }
    },
    {
    ....
  ]
}

Basically - I want to turn the resultset in to a big old JSON object, including all that lovely related data. Now, for bonus points, it's likely to be bringing down a pretty big JSON object (1mb or so) with some very nested data - ten or twelve objects deep, let's say - is there a nice way of avoiding the performance problems that it'll bring?



125.8k
Accepted
answer

Is this code in your view or controller? I feel like it should be in your controller.

In any case - I believe Phalcon's model has a toArray() method that may help.