nexus
nexus

Reputation: 170

Including One-To-One association from both sides

I have two models that need to be connected in a one-to-one association: Coach and Team. A team only has one coach and a coach only has one team.

I need to be able to include from both sides: sometimes I query the Coach and include the Team, sometimes I query the Team and include the Coach.

Now I'm not sure: do I need to create reference columns on each table (CoachId in table "Teams" and TeamId in table "Coaches")?

I have tried creating those two columns and established the association like so:

module.exports = models => {
  models.Coach.hasOne(models.Team)
  models.Team.belongsTo(models.Coach)
}

But for some reason, when I'm creating a Coach and setting the existing TeamId, the TeamId column stays empty. Also, even if it would have been filled, it feels odd to also have to update the Coach row with the correct TeamId.

Can it all be accomplished in one write and then be queried from both sides as suggested above? Feels like I still have not understood something fundamental about Sequelize, even after working with it for a while.

Thanks!

Upvotes: 0

Views: 85

Answers (1)

Anirudh AV
Anirudh AV

Reputation: 36

to query from both sides, you need to use a through table

module.exports = models => {
  models.Coach.hasOne(models.Team)
  models.Team.belongsTo(models.Coach, {through: 'TeamCoach'})
}

TeamCoach will have primary keys from both tables linked such that it can allow for a bi directional query.

Upvotes: 1

Related Questions