无法实现续集外键映射/约束

时间:2019-10-22 11:05:55

标签: sequelize.js

我正在创建3个表,user_details,user_role,role,期望的模式在下面提到。

    我不能达到的目标? :约束/映射到user_details表的user_id和user_role表的user_id。我只能为role和user_role表实现对role_id的约束。
  • 使用“ sequelize”:“ ^ 5.19.4”,

我想实现以下映射:

CREATE TABLE `role` (
  `id` bigint(20) NOT NULL ,
  `authority` varchar(255) NOT NULL,
  PRIMARY KEY (`id`),
  `createdAt` datetime NOT NULL,
  `updatedAt` datetime NOT NULL,
  UNIQUE KEY `UK_irsamgnera6angm0prq1kemt2` (`authority`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `user_role` (
  `user_id` int(24) UNSIGNED NOT NULL AUTO_INCREMENT,
  `role_id` bigint(20) NOT NULL,
  `createdAt` datetime NOT NULL,
  `updatedAt` datetime NOT NULL,
  PRIMARY KEY (`user_id`,`role_id`),
  KEY `FKa68196081fvovjhkek5m97n3y` (`role_id`),
  CONSTRAINT `FK859n2jvi8ivhui0rl0esws6o` FOREIGN KEY (`user_id`) REFERENCES `user_details` (`id`),
  CONSTRAINT `FKa68196081fvovjhkek5m97n3y` FOREIGN KEY (`role_id`) REFERENCES `role` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `user_details` (
  `id` int(24) NOT NULL AUTO_INCREMENT,
  `created` datetime NOT NULL,
  `mobile` varchar(10) NOT NULL,
  `pin` varchar(255) NOT NULL,
  `enabled` bit(1) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


创建3个单独的模型文件。

Role.ts

export class Role extends Model<Role> {
  public role_id!: number;
  public authority!: string;
  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;
}
console.log("inside role class")
Role.init(
  {
    role_id: {
      type: DataTypes.INTEGER.UNSIGNED,
      autoIncrement: true,
      primaryKey: true,
      unique : true
    },
    authority: {
      type: new DataTypes.STRING(128),
      allowNull: false
    }
  },
  {
    tableName: "role" ,
    freezeTableName : true ,
    modelName: "role",
    sequelize: mysqlConnection // this bit is important
  }
);

// Run below query to create table

Role.sync({force:true}).then(() => console.log("Role table created"));
//Role.hasOne(User , {foreignKey: 'id'})

user-details.ts

export class UserDetails extends Model {
    public user_id!: number;
    public mobile!: string;
    public pin!: string;
    public enabled!: boolean;  
    public readonly createdAt!: Date;
    public readonly updatedAt!: Date;  

  }

  UserDetails.init(
      {
        user_id: {
          type: DataTypes.INTEGER.UNSIGNED,
          autoIncrement: false,
          primaryKey: true
        },
        mobile: {
          type: DataTypes.STRING(10),
          allowNull: false
        } ,
        pin: {
          type: DataTypes.STRING(255),
          allowNull: false
        } ,
        enabled: {
          type: DataTypes.BOOLEAN,
          allowNull: false
        } ,
      },
      {
        freezeTableName: true,
        tableName :"user_details",
        modelName: "user_details",
        sequelize: mysqlConnection // this bit is important
      }
    );

// BelongsTo will add the foreignKey on the source where hasOne will add on the targe
// Run below query to create table

UserDetails.belongsTo(UserRole , {foreignKey :'user_id' , targetKey : 'user_id' , constraints:false})
UserDetails.sync({force:true}).then(() => console.log("User table created"));

-----------------------

user-role.ts
export class UserRole extends Model<UserRole> {
    public user_id!: number;
    public role_id!: number;
    public readonly createdAt!: Date;
    public readonly updatedAt!: Date;

}

UserRole.init(
    {
        user_id: {
            type: DataTypes.INTEGER.UNSIGNED,
            autoIncrement: true,
            primaryKey: true,
        },
        role_id: {
            type: DataTypes.INTEGER.UNSIGNED,
            allowNull: false,
            primaryKey: true,
            autoIncrement: false,
        },
    },
    {   
        tableName : "user_role",
        freezeTableName : true,
        modelName: "user_role",
        sequelize: mysqlConnection // this bit is important
    }
);

// BelongsTo will add the foreignKey on the source where hasOne will add on the target
// Run below query to create table
//UserRole.hasMany(Role)
//UserRole.hasMany(User, { foreignKey: 'user_id' } )
// User.belongsTo(UserRole , {foreignKey :'user_id' , targetKey : 'user_id'})
//UserRole.belongsTo(User, { foreignKey: 'user_id', targetKey: 'user_id' })

//UserRole.belongsTo(UserDetails, { foreignKey: 'user_id', targetKey: 'user_id' })
//UserDetails.hasMany(UserRole, { foreignKey: 'user_id' , sourceKey : 'user_id' } )
//UserDetails.belongsTo(UserRole , {foreignKey :'user_id' , targetKey : 'user_id' , constraints:false})


UserRole.belongsTo(Role, { foreignKey: 'role_id', targetKey: 'role_id' })

UserRole.sync({force:true}).then(() => console.log("user_role table created"));

执行上述代码会创建以下日志:

Executing (default): CREATE TABLE IF NOT EXISTS `user_role` (`user_id` INTEGER UNSIGNED auto_increment , `role_id` INTEGER UNSIGNED NOT NULL , `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`user_id`, `role_id`), FOREIGN KEY (`role_id`) REFERENCES `role` (`role_id`) ON DELETE NO ACTION ON UPDATE CASCADE) ENGINE=InnoDB;
Role table created
Executing (default): CREATE TABLE IF NOT EXISTS `user_details` (`user_id` INTEGER UNSIGNED , `mobile` VARCHAR(10) NOT NULL, `pin` VARCHAR(255) NOT 
NULL, `enabled` TINYINT(1) NOT NULL, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`user_id`)) ENGINE=InnoDB;
Executing (default): SHOW INDEX FROM `user_role`
Executing (default): SHOW INDEX FROM `user_details`
user_role table created
User table created

所以我的理解是为user_details表创建了外键“ user_id”,但未通过user_role表的“ user_id”列进行映射/约束。因此,user_details表的user_id不受限制。

无济于事,我尝试了所有我能想到的在注释行中提及的组合。

0 个答案:

没有答案