首页 > 解决方案 > 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 中手动更改了它) HeidiSql

当我尝试插入数据库时​​,出现以下错误

HeidiSql错误

标签: node.jsmariadbsequelize.js

解决方案


您可以尝试使用sequelize.literalsequelize.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
    },

推荐阅读