如何阻止sequelize向MYSQL表发送默认值?
控制台日志:如何阻止sequelize向MYSQL表发送默认值?,mysql,node.js,sequelize.js,Mysql,Node.js,Sequelize.js,控制台日志: Executing (default): INSERT INTO `testtables` (`id`,`forgot_code`,`customer_id`) VALUES (DEFAULT,610,199) 如何停止sequelize向我的列id发送DEFAULT值? 既然主键已处于自动递增状态,如何停止将sequelize插入主键 我的代码: var TestTable= sequelize.define('testtables', { id:{ t
Executing (default): INSERT INTO `testtables` (`id`,`forgot_code`,`customer_id`) VALUES (DEFAULT,610,199)
如何停止sequelize向我的列id
发送DEFAULT
值?
既然主键已处于自动递增状态,如何停止将sequelize插入主键
我的代码:
var TestTable= sequelize.define('testtables', {
id:{
type:Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
forgot_code:Sequelize.INTEGER,
customer_id:Sequelize.INTEGER
},{
timestamps: false,
});
必须从模型定义中删除
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
,insert将经历一段时间的延迟回复,但我对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级别找到了此解决方案:我很好奇:这真的会导致问题吗?如果是,错误是什么?我通常不会编写这样的查询,但它似乎与根本不引用insert语句中的列具有完全相同的效果(这会隐式插入“default”,它仍然隐式地
NULL
,即使列不是NULL
)并应导致插入下一个自动增量值。