gpt4 book ai didi

mysql - Sequelize MySQL Migration - 唯一为 false

转载 作者:行者123 更新时间:2023-12-03 22:16:59 25 4
gpt4 key购买 nike

我正在尝试在 Sequelize 和 MySQL 中编写一个迁移,它将唯一属性设置为 false。到目前为止,这是我的方法:

module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.changeColumn("users", "name", {
type: Sequelize.STRING,
allowNull: false,
unique: true,
});
await queryInterface.changeColumn("users", "email", {
type: Sequelize.STRING,
allowNull: false,
unique: true,
});
},

down: async (queryInterface, Sequelize) => {
await queryInterface.changeColumn("users", "name", {
type: Sequelize.STRING,
allowNull: true,
unique: false,
});
await queryInterface.changeColumn("users", "email", {
type: Sequelize.STRING,
allowNull: true,
unique: false,
});
},
};

向上迁移像 charme 一样工作,向下迁移对 allowNull 有效,但对 unique 属性无效。我是 Sequelize 的新手,所以我想知道这里出了什么问题。有人可以帮帮我吗?

非常感谢您。

最佳答案

Sequelize 具有“removeConstraint”方法,您可以使用该方法移除属性的约束。

public removeConstraint(tableName: string, constraintName: string, options: Object): Promise

实际上,如果您在创建时不指定“constraintName”,它应该是“attributename_unique_key”的形式。

请尝试使用这种方式

module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.changeColumn("users", "name", {
type: Sequelize.STRING,
allowNull: false,
unique: true,
});
await queryInterface.changeColumn("users", "email", {
type: Sequelize.STRING,
allowNull: false,
unique: true,
});
},

down: async (queryInterface, Sequelize) => {
await queryInterface.changeColumn("users", "name", {
type: Sequelize.STRING,
allowNull: true,
});
await queryInterface.removeConstraint("users", "name_unique_key");
await queryInterface.changeColumn("users", "email", {
type: Sequelize.STRING,
allowNull: true,
});
await queryInterface.removeConstraint("users", "email_unique_key");
},
};

有关更多信息,请查看文档 here

关于mysql - Sequelize MySQL Migration - 唯一为 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66399694/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com