【发布时间】:2020-07-19 04:34:56
【问题描述】:
当我使用 sequelize create 时,它总是更新表中的数据而不是创建一个新数据(id 是自动递增的)
当我从 mysql 工作台运行相同的命令时,它会正确创建新数据。也许我在我的设置中遗漏了一些东西...... 续集版本:sequelize:^5.22.3 Mysql 版本:5.5.62
型号:
const Merchants = sequelize.define('merchant', {
merchant_id: { type: Sequelize.STRING(12), allowNull: false },
shop_id: { type: Sequelize.STRING(75), allowNull: false },
status: { type: Sequelize.TINYINT(4), allowNull: false },
credits: { type: Sequelize.INTEGER(11), allowNull: false },
});
创建:
Merchants.create({
merchant_id: getNewMerchantID(),
shop_id: shop_id,
status: status,
credits: credits
}).then(merchants => {
console.log(` created merchant: ${shop_id}`);
}).catch(error => {
console.log(` error creating merchant: ${error}`);
})
控制台日志
Executing (default): SHOW INDEX FROM `merchants`
Executing (default): INSERT INTO `merchants` (`id`,`merchant_id`,`shop_id`,`status`,`credits`) VALUES (DEFAULT,?,?,?,?);
[merchantController] created merchant: SHOP_ID1
顺便说一句,我对 findOneOrCreate 也有同样的问题,它从不插入新记录,总是更新数据库上的最后一条记录
findOrCreate
try {
//check if exists
const [merchant, created] = await Merchants.findOrCreate({
where: { shop_id: shop_id },//find this
defaults: {//or create this
merchant_id: getNewMerchantID(),
//shop_id: shop_id, // does not need to repeat, its in the where clause
status: status,
credits: credits
}
});
console.log(`[Merchants] created merchant: ${shop_id} [${created}]`);
return created;
} catch (error) {
console.log(`[Merchants] error creating Merchants: ${error}`);
return false;
}
【问题讨论】:
标签: mysql sequelize.js