Arrays of joined ids

Thanks to a helpful stack overflow response, I now have an improved solution to my problem of needing to add arrays of joined ids to JSON output from CakePHP 3. The output from a test containing Widget models that can each have many Foos looks something like this:


To easily and automatically add this capability to any model I wanted, I created a new class extending Cake’s  Table , which I called “ApiTable”:

The  formatWithJoinedIds() method adds an array called  model_ids for each model, from an input list, that is associated with this one through a ‘BelongsToMany’ or ‘HasMany’ join, without including the contents of the associated models. It is intended to be called from the  findApi() method, which simply performs a query containing the passed-in desired list of models and formats the results.

The custom finder is straightforward:

The array  $includeIdsFor should contain strings identifying the associated properties whose joined ids should be included. For instance, if a Widget has many associated Foos, Bars, and Bazzes, the ids of the foos and bars would be included in the output by passing  ['Foos', 'Bars'].

The result formatter, used to add the calculated fields containing the id arrays, is a little longer but not much more complicated:

This routine generates an array of all properties of the current model that point to many of another model. It then iterates over these properties, and for each one iterates over all of the foreign models to collect an array of their ids. The resulting array is added as a new property to the row, and the foreign models themselves are unset if they are not to be included in the output.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.