Wednesday, 7 June 2017

Sequelize: How to fetch polymorphic associations in one query

Using node.js and Sequelize, I have a table called Collection that has many polymorphic items associated using a through table called CollectionItem. When I fetch a collection, I’d like those items to be fully populated in the JSON response

Example: When I GET /collections/3138971957830090752 I want it to return something like

// this is a collection dictionary with an array of 
// `collectionItems` that contain polymorphic associations
{
  "uid": "3138971957830090752",
  "title": "Hi there",
  "createdAt": "2017-06-06T19:39:36.953Z",
  "updatedAt": "2017-06-06T19:39:36.953Z",
  "collectionItems": [{
      "uid": "3138972684428247040",
      "propertyOnModelA": "this is the Model A record being expanded",
    },
    {
      "uid": "3138972684428249291",
      "propertyOnModelB": "this is the Model B record being expanded",
    },
    {
      "uid": "3138972684428219233",
      "propertyOnModelC": "this is the Model C record being expanded",
    },
    {
      "uid": "3138972684428929103",
      "propertyOnModelA": "this is another Model A record being expanded",
    }]
}

i.e. the response of collectionItems is a mix of different concrete item types in an array like [ModelA, ModelB, ModelC, ModelA] where each model is an expanded dictionary that can be parsed into an object on the client

What’s the best way to do this so it’s all fetched within one query versus fetching the individual items and then doing more fetches to fully populate them?



via iwasrobbed

No comments:

Post a Comment