如何阻止sequelize向mysql表发送默认值?

ndh0cuux  于 2021-06-23  发布在  Mysql
关注(0)|答案(2)|浏览(348)

控制台日志:

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,
});
kmpatx3s

kmpatx3s1#

回复有点晚,但我对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
      }
    })
  },
})

更新:在db级别找到此解决方案:https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_no_auto_value_on_zero

oyxsuwqo

oyxsuwqo2#

你必须移除 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 ,插入将通过

相关问题