Chris
Chris

Reputation: 14218

js sequelize chain association accessors

I have three models: Url, Action, Container I would like to get the Container of a Url through the following relations:

db.Url.belongsTo(db.Action, { foreignKey: 'action_id'});
db.Action.belongsTo(db.Container, { foreignKey: 'container_id'});

I was hoping for something like:

db.Url.findOne(...).getAction().getContainer()

However it only seems to work when I work with the entities one after another.

i.e. query the db for the url. Then call url.getAction() and then getContainer.

So it is three separate querys instead of one.

Upvotes: 1

Views: 472

Answers (1)

Ellebkey
Ellebkey

Reputation: 2301

So you are asking for a nested include? I don't quite understand what you need to find, the Container through a given Url.id?? Anyaways you're looking for something like this

db.Url.find({
  include: [
    {
      model: db.Action,
      include : [{
        model: db.Container
      }]
    }
  ]
})
.then(function(response) {
  return res.json(response);
})
.catch(function (err) {
  // more code...
});

This will a return a single json with all corresponding associations.

Upvotes: 3

Related Questions