sequelize:如何创建约束名称

Sug*_*san 5 sequelize.js

我有一个包含以下行的 sql 查询

CONSTRAINT `some_key_1` FOREIGN KEY (`another_table_uuid`) REFERENCES `another_table` (`uuid`),
  CONSTRAINT `some_key_2` FOREIGN KEY (`another_table_uuid`) REFERENCES `another_table` (`uuid`)
Run Code Online (Sandbox Code Playgroud)

我在续集中创建了一个关联,如下所示:

current_table.associate = models => {

    current_table.belongsTo(models.another_table, {
        foreignKey: "another_table_uuid",
        targetKey: "uuid",
    });
    current_table.belongsTo(models.another_table, {
        foreignKey: "another_table_uuid",
        targetKey: "uuid",
    });
Run Code Online (Sandbox Code Playgroud)

});

但如何在这里添加约束名称

mysql 中还有这一行:

钥匙somekey_name_UUIDsome_table_uuid

我如何将其更改为续集。

小智 2

我知道我迟到了三年多,开始学习sequelize,却碰巧遇到了同样的问题(根本不是问题,但这有点让我烦恼)。

据我所知,没有属性可以将自定义名称添加到由sequelize定义的外键,但是您可以通过使用sequelize实例的查询接口来添加名称。

通过model添加外键(外键名称由sequelize定义):

users.init(
  {
    user_id: { type: DataTypes.INTEGER },
    username: { type: DataTypes.STRING(20) },
    user_rol: {
      type: DataTypes.INTEGER,
      allowNull: false,

      //Adding foreign key -> generates CONSTRAINT modelName_magicString_NUMBER
      references: {
        model: "rols",
        key: "rol_id",
      },
      onDelete: "RESTRICT",
      onUpdate: "CASCADE",
    },
  },
  {
    sequelize,
    modelName: "users",
    freezeTableName: true,
    timestamps: false,
  }
);

Run Code Online (Sandbox Code Playgroud)

通过queryInterface添加外键(自定义外键名称):

sequelize.getQueryInterface().addConstraint("users", {
  type: "FOREIGN KEY",
  fields: ["user_rol"],
  name: "fk_user_rol", // Custom name -> generate CONSTRAINT fk_user_rol
  references: { table: "rols", field: "rol_id" },
})
*Note: this just add the constraint to the database, you should already 
have a table and you must define or init your models to sequelize by apart.
Run Code Online (Sandbox Code Playgroud)

如果您使用sequelize-cli 进行迁移,您可以:

async up(queryInterface, Sequelize){
  await queryInterface.createTable("tableName", {
    //Your attributes here...
  })
  await queryInterface.addContraint("tableName", {
    //Your code goes here...
  })
}
Run Code Online (Sandbox Code Playgroud)

如果您知道通过模型为外键添加自定义名称的方法,请告诉我。