Sequelize Mariadb如何将主键的默认值设置为uuid?
Sequelize MariadDb how to setup default value of priamary key to be uuid?
我已经阅读了一段时间的文档,但我无法理解这一点。我需要将所有表的 primaryKey 的默认值设置为 uuid。这就是我现在拥有的。
***cityModel***
module.exports = (sequelize, type) => {
return sequelize.define('Cities', {
id: {
type: type.UUID,
defaultType: type.UUIDV4,
defaultValue: type.UUIDV4,
allowNull: false,
primaryKey: true
},
code: {
type: type.ENUM(...enumCode),
allowNull: false
},
***another fields***
};
正如你在图片中看到的,我需要将它从sequelize设置为默认的uuid(),否则我会在插入时出错。 (我没有默认,我在 HeidiSql 中手动更改了它)
当我尝试插入数据库时出现以下错误
您可以尝试在 defaultValue
选项中使用 sequelize.literal
或 sequelize.fn
,如下所示:
id: {
type: type.UUID,
defaultType: type.UUIDV4,
defaultValue: sequelize.literal('UUID()'),
// defaultValue: sequelize.fn('UUID'),
allowNull: false,
primaryKey: true
},
更好的方法是在数据库中设置 PK 的默认值(在迁移或在数据库中创建结构的初始 SQL 脚本中),在这种情况下,您可以在模型中设置 PK像这样:
id: {
type: type.UUID,
defaultType: type.UUIDV4,
allowNull: false,
primaryKey: true,
autoIncrement: true // this tells Sequelize that a value is generated by a DB and Sequilize does not indicate it itself at all
},
我已经阅读了一段时间的文档,但我无法理解这一点。我需要将所有表的 primaryKey 的默认值设置为 uuid。这就是我现在拥有的。
***cityModel***
module.exports = (sequelize, type) => {
return sequelize.define('Cities', {
id: {
type: type.UUID,
defaultType: type.UUIDV4,
defaultValue: type.UUIDV4,
allowNull: false,
primaryKey: true
},
code: {
type: type.ENUM(...enumCode),
allowNull: false
},
***another fields***
};
正如你在图片中看到的,我需要将它从sequelize设置为默认的uuid(),否则我会在插入时出错。 (我没有默认,我在 HeidiSql 中手动更改了它)
当我尝试插入数据库时出现以下错误
您可以尝试在 defaultValue
选项中使用 sequelize.literal
或 sequelize.fn
,如下所示:
id: {
type: type.UUID,
defaultType: type.UUIDV4,
defaultValue: sequelize.literal('UUID()'),
// defaultValue: sequelize.fn('UUID'),
allowNull: false,
primaryKey: true
},
更好的方法是在数据库中设置 PK 的默认值(在迁移或在数据库中创建结构的初始 SQL 脚本中),在这种情况下,您可以在模型中设置 PK像这样:
id: {
type: type.UUID,
defaultType: type.UUIDV4,
allowNull: false,
primaryKey: true,
autoIncrement: true // this tells Sequelize that a value is generated by a DB and Sequilize does not indicate it itself at all
},