Sequelize: Defining Associations

Viewed 328

Reading the documentation of Sequelize I'm in some level confused, what Sequelize will provide automatically for us and what we need to explicitly tell it. I have two models: User and Post. As you have guessed a User can have multiple Posts and a Post belongs only to one User. Setting the respective relationships will look so:

Post.associate = (models) => {
  Post.belongsTo(models.users, {
    as:'user',
    foreignKey: {
      name: 'user_id',
      allowNull: false
    }
  }
}

User.associate = (models) => {
  User.hasMany(models.posts, {
    as:'posts',
    onDelete:'CASCADE',
    onUpdate:'CASCADE' 
  }
}

My question is: should I specify the foreignKey one more time when declaring the hasMany association, or it is enough for Sequelize to have the foreignKey in one of the declared relationships between two models (in the example - belongsTo)?

1 Answers

From what I think happens:

  • Sequelize goes through all your association one by one
  • If you already provided a foreign key name then fine
  • Else it will guess/name the foreign key on its own

Like what it says about options.foreignKey in docs e.g. for belongsTo : https://sequelize.org/master/class/lib/model.js~Model.html#static-method-belongsTo (same description for hasOne, hasMany, belongsToMany )

options.foreignKey || string OR object || optional

The name of the foreign key attribute in the source table or an object representing the type definition for the foreign column (see Sequelize.define for syntax). When using an object, you can add a name property to set the name of the column. Defaults to the name of target + primary key of target

If sequelize is guessing your foreignKey names then you will face issues only if your foreignKey name is not matching (tableName + Id) OR (tableName + _ + id)

Hence, better to give foreignKey names on your own to both sides of associations to never face any issues going further.

Related