Skip to content Skip to sidebar Skip to footer

Sequelize - Cannot Add Foreign Key Constraint

I'm trying to set a 1:1 relation between two tables. RefreshToken table will have two foreignKey releated to Users table, as in this image: I used sequelize-auto to generate my se

Solution 1:

This is common type error mainly occurs because of

1. When the primary key data type and the foreign key data type did not matched

return sequelize.define('RefreshToken', {
    userId: {
      type: DataTypes.INTEGER(11), // The data type defined here and 
      references: {
        model: 'Users',
        key: 'idUsers'
      }
    }, 


return sequelize.define('Users', {
    idUsers: {
      type: DataTypes.INTEGER(11),  // This data type should be the same
    },

2. When the referenced key is not a primary or unique key.

You can not have two primary keys, so other referenced keys should be defined unique. unique:true

return sequelize.define('Users', {
    idUsers: {
      primaryKey: true  
    },
    mail: {
      type: DataTypes.STRING(45),
      allowNull: false,
      primaryKey: true// You should change this to 'unique:true'. you cant hv two primary keys in one table. 
    }

Solution 2:

I see two issues:

No table should contain two primary keys and userId shouldn't be in integer it should be a UUID.

I had a foreign key set to INT and it gave me error:

Unhandled rejection SequelizeDatabaseError: foreign key constraint "constraint_name_here" cannot be implemented

Try changing:

userId: {
  type:DataTypes.INTEGER(11),
  allowNull:false,
  primaryKey:true,
  references: {
    model:'Users',
    key:'idUsers'
  }
},

To

userId: {
  type:DataTypes.UUID,
  allowNull:false,
  foreignKey:true,
  references: {
    model:'Users',
    key:'idUsers'
  }
},

Post a Comment for "Sequelize - Cannot Add Foreign Key Constraint"