sequelize - Cannot add foreign key constraint

后端 未结 2 801
既然无缘
既然无缘 2020-12-31 07:02

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 t

相关标签:
2条回答
  • 2020-12-31 07:20

    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. 
        }
    
    0 讨论(0)
  • 2020-12-31 07:38

    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'
      }
    },
    
    0 讨论(0)
提交回复
热议问题