sequelize - Cannot add foreign key constraint

后端 未结 2 800
既然无缘
既然无缘 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. 
        }
    

提交回复
热议问题