FlormModel extends Bookshelf's Model class to allow for arbitrary side-loads on the model definition. The example loads IDs from the profiles table using the edges
table as a join table.
Each element on sideloadIds should be a function that returns a promise. The promise should resolve to some value (doesn't matter what), which will be set on the actual Models during fetch or fetchAll calls.
This is ideal for either:
- creating loosely-coupled relations for an API, as (for example) the JSON API spec prefers relations to only include a set of ids (like
reply_ids: [1, 2, 3]
instead ofreplies: [{reply1}, {reply2}, {reply3}]
). - using more complicated SQL queries in your model definition. My own needs have some relations that don't fit into a clean hasMany style query (there's some complicated joins).
NOTE: there's no error handling in this example, as that would clutter it up. Do it yourself.
If you don't want the sideload code to fire off automatically on fetching (it does generate more queries), you can go ahead and just remove the fetch and fetchAll extensions and call FlormModel.sideload('thing_ids'), .sideload(['thing_ids', 'other_thing_ids']), or .sideload() on your own time.
Thanks for this! An alternative for people who would rather chain it onto the fetch would be to write something like the following: