node.js - Sequelize MariadDb如何将主键的默认值设置为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 中手动更改了它)
当我尝试插入数据库时,出现以下错误
解决方案
您可以尝试使用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
},
推荐阅读
- c# - 无法转换类别名称而不是类别 ID
- docker - 如何构建和运行 Docker 镜像?
- python - 递归方法不返回值
- python-3.x - plt.show() 的问题,没有返回错误但没有图像显示
- r - 是否可以仅使用 R 中的起点和终点信息绘制图形(一种箱线图)?
- go - 是否将 net.Dialer 上的超时和 Connection 上的最后期限设置为相同的行为?
- c# - 在 Visual Studio 中编辑的 Unity 脚本不提供自动完成功能...2020
- javascript - 我想做一个 Discord.js 反应收集器、计数器、计时器和角色 dm
- angular - 如何在 Angular 组件中显示 HTML Dom/Angular 组件?
- c - 为什么指向结构的指针在函数中不可覆盖?