【问题标题】:How to stop sequelize from sending default value to MYSQL table?如何阻止 sequelize 将默认值发送到 MYSQL 表?
【发布时间】:2021-09-16 18:39:11
【问题描述】:

控制台日志:

Executing (default): INSERT INTO `testtables` (`id`,`forgot_code`,`customer_id`) VALUES (DEFAULT,610,199)

如何阻止 sequelize 将 DEFAULT 值发送到我的列 id ? 我如何阻止 sequelize 插入我的主键,因为它已经处于自动增量状态?

我的代码:

var TestTable= sequelize.define('testtables', {
    id:{
        type:Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    forgot_code:Sequelize.INTEGER,
    customer_id:Sequelize.INTEGER   
},{
    timestamps: false,
});

【问题讨论】:

  • 我很好奇:这真的会导致问题吗?如果是这样,错误是什么?我通常不写这样的查询,但它似乎与根本不引用插入语句中的列具有完全相同的效果(它隐式插入“默认”,它隐式仍然是NULL,即使列是NOT NULL),应该会插入下一个自动增量值。

标签: mysql node.js sequelize.js


【解决方案1】:

回复有点晚,但我对 Percona 有类似的问题。所以我们的解决方案是添加一个钩子:

new Sequelize(database, username, password, {
  dialect: 'mysql',

  // FIXME: This is a temporary solution to avoid issues on Percona when Sequelize transform insert query into
  // INSERT INTO [TABLE_NAME] (`id`, ...) VALUES (DEFAULT, ...)
  hooks: {
    beforeCreate: ((attributes) => {
      if (attributes
        && attributes.dataValues
        && attributes.dataValues.hasOwnProperty('id')
      ) {
        delete attributes.dataValues.id
      }
    })
  },
})

更新:在数据库级别找到了这个解决方案:https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_no_auto_value_on_zero

【讨论】:

    【解决方案2】:

    1.删除所有节点模块 2.重新安装节点模块(npm install)

    现在,问题将得到解决。这对我有用。

    【讨论】:

      【解决方案3】:

      您必须从模型定义中删除 autoIncrement: true。现在,插入而不提供id 值将失败。例如下面的代码会失败

      const User = sequelize.define('user', {
        id: {
          type: Sequelize.INTEGER,
          primaryKey: true,
          // autoIncrement: true
        },
        username: Sequelize.STRING,
      });
      
      sequelize.sync({ force: true })
        .then(() => User.create({
          username: 'test123'
        }).then((user) => {
          console.log(user);
        }));
      

      但是,如果您取消注释 autoIncrement: true,插入将通过

      【讨论】:

        猜你喜欢
        • 2015-08-18
        • 1970-01-01
        • 1970-01-01
        • 2013-09-26
        • 2016-05-01
        • 1970-01-01
        • 2023-03-20
        • 1970-01-01
        • 2018-06-13
        相关资源
        最近更新 更多