控制台日志:
Executing (default): INSERT INTO `testtables` (`id`,`forgot_code`,`customer_id`) VALUES (DEFAULT,610,199)
如何停止将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,
});
答案 0 :(得分:0)
您必须从模型定义中删除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
,则插入将通过
答案 1 :(得分:0)
回复有点晚,但是我对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
上找到了此解决方案