【问题标题】:Sequelize Create or FindOrCreate never creates new records, only updates previous onesSequelize Create 或 FindOrCreate 从不创建新记录,只更新以前的记录
【发布时间】: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


    【解决方案1】:

    发现问题 我正在调用代码以在 sequelize.sync 的承诺中创建此模型的新记录,这显然总是删除表并插入新数据,这使它看起来像是在覆盖

    sequelize.sync({ force: true }).then(syncRes => {
         createMerchant("SHOP_ID1", 1, 999, "TOKEN");
       }).catch(error => {
         console.log(`sequelize synch error: ${error}`);
       });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-08
      • 2023-01-12
      • 2011-12-09
      • 2012-07-25
      相关资源
      最近更新 更多