node.js - Sequelize Mariadb 如何将主键的默认值设置为 uuid?

标签 node.js mariadb sequelize.js

我现在正在阅读文档一段时间,但我无法弄清楚这一点。我需要将所有表上的 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 中手动更改了它)
HeidiSql
当我尝试插入数据库时​​出现以下错误
HeidiSql error

最佳答案

您可以尝试在 sequelize.literal 选项中使用 sequelize.fndefaultValue ,如下所示:

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/

相关文章:

javascript - 从 Moment JS 获取 JavaScript 本地日期

ruby-on-rails - 如何锁定表以防止在 Rails 中使用记录创建?

mysql - TypeORM delete using WHERE with OR operator using Repository

node.js - 属性 'User' 在快速 typescript 中的 'typeof db' Sequelize 类型上不存在

javascript - Nodejs for循环创建具有动态内容的动态路由

javascript - 通过 Fetch Api 发布请求时 Req.body 未定义

node.js - 通过socket.io向所有连接到nodejs服务器的客户端广播更新的数据

mysql - ORDER BY 列从连接表表现

mysql - docker-compose:mariadb - 连接被拒绝

orm - 如何描述旧表与 Sequelize 模型对象的一对多连接?