【问题标题】:Sequelize Alter always set all data table foreign key to nullSequelize Alter总是将所有数据表外键设置为null
【发布时间】:2021-08-30 11:02:20
【问题描述】:

错误说明

使用选项alter: true 运行sequelize sync 后,表中的所有外键都设置为null

await sequelize.sync({ alter: true }).then(async (result) => {
      await initDataUserGroup();
      await initDataUserAdmin();
      await initDataGateType();
});

这是我的一个具有外键的模型:

const { DataTypes } = require("sequelize");
const { sequelize } = require("../services/DatabaseService");

const UserGroup = require("./UserGroup");
const Biodata = require("./Biodata");

const User = sequelize.define("user", {
  username: {
    type: DataTypes.STRING,
    allowNull: false,
    unique: true,
    validate: {
      notNull: {
        msg: "Username must not be empty",
      },
      notEmpty: true,
    },
  },
  email: {
    type: DataTypes.STRING,
    allowNull: false,
    unique: true,
    validate: {
      notNull: true,
      notEmpty: true,
      isEmail: true,
    },
  },
  password: {
    type: DataTypes.STRING,
    allowNull: false,
    validate: {
      notNull: true,
      notEmpty: true,
    },
  },
});

User.UserGroup = User.belongsTo(UserGroup);
User.Biodata = User.hasOne(Biodata, {
  foreignKey: "userId",
  as: "biodata",
});

module.exports = User;

您预计会发生什么?

在使用选项{ alter: true } 运行同步后,不应将所有外键设置为空

实际发生了什么?

user中的userGroupId为空,表biodata中的userId也为空。

环境

  • 续集版本:^6.6.5
  • Node.js 版本:12.9.1
  • 方言:SQLite (SQLite3)

来自我的问题:https://github.com/sequelize/sequelize/issues/13464

谁能帮帮我?

【问题讨论】:

    标签: node.js sqlite express sequelize.js


    【解决方案1】:

    经过几天的努力,我设法通过在同步前后禁用和重新启用外键来解决它:

    await sequelize.query("PRAGMA foreign_keys = false;");
    await sequelize
          .sync({ alter: true })
          .then(async (result) => {
            await initDataUserGroup();
            await initDataGateType();
          })
          .catch((errorMessage) => console.error("sync error = ", errorMessage));
    await sequelize.query("PRAGMA foreign_keys = true;");
    

    请随时告诉我比当前解决方案更好的解决方案。

    【讨论】:

      猜你喜欢
      • 2019-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-01
      • 2021-12-03
      • 1970-01-01
      相关资源
      最近更新 更多