我现在正在阅读文档一段时间,但我无法弄清楚这一点。我需要将所有表上的 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 中手动更改了它)当我尝试插入数据库时出现以下错误
最佳答案
您可以尝试在 sequelize.literal
选项中使用 sequelize.fn
或 defaultValue
,如下所示:
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
},
关于node.js - Sequelize Mariadb 如何将主键的默认值设置为 uuid?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64039189/