Search code examples
databasepostgresqlsequelize.jsmodel-associations

sequelize return association of manually defined join table


I'm using Sequelize with Postgres. Two of my tables (estimatorList and subcontractor) are joined by a manually defined table (estimatorSubsList).

db.subcontractor.belongsToMany(db.estimatorList, { through: db.estimatorSubsList });
db.estimatorList.belongsToMany(db.subcontractor, { through: db.estimatorSubsList });

estimatorSubsList has an id and other fields but it is also associated to contact via

db.contact.hasMany(db.estimatorSubsList);

When I query the database for estimatorList with a particular id and return the subcontractor (and tables associated with subcontractor) associated with this -

db.estimatorList.findById(estimatorListId, {include:  [ { 
            model: db.subcontractor, 
            include: [  db.location, etc, etc ]
     }
    ]} )

It returns all the correct information. It also automatically returns estimatorSubsList with the contactId inside each subcontractor object. EG:

estimatorSubsList: 
{ contactId: 1
  createdAt: ""
  estimatorListId: 1
  id:2
  otherFields:false
  subcontractorId: 2
  updatedAt:"" 
}

My question is, is it possible to get not only the contactId, but the whole contact record itself? I'm unsure how to change the default information being returned or if that is even possible. I've tried including the estimatorSubsList model and including contact from that, but it doesn't like me trying to include estimatorSubsList at all.

Cheers all


Solution

  • It is not possible for a through relation table to have associations. Instead, you should model it as a separate model and include it as such:

    EstimatorList.findAll({
      include: [{
        model: EstimatorSubsList,
        include: [Contact, Subcontractor]
      }]
    })
    

    Make sure you have all associations set up in both directions.