sequelize 批量更新

159 阅读1分钟

栗子

比如这边有2张表,题目和维度表。 其中呢,题目表中有维度名称,因此一旦更新了维度表的维度名称,就需要批量更新下题目表中的维度名称

代码

思路

  1. 通过题目表中的维度id找到,所有需要更新的题目
  2. 搜集题目id,并保存
  3. 利用Op.in实现批量更新
  const qs = await Question.findAll({
    where: {
      dimension_id,
    },
  });
  let ids = [];
  qs.forEach((item) => {
    ids.push(item.dataValues.id);
  });
  console.log(ids);
  if (ids.length) {
    const update = await Question.update(
      {
        dimension_name: name,
      },
      {
        where: {
          dimension_id: {
            [Op.in]: ids,
          },
        },
      }
    );
    if (update[0] <= 0) {
      throw new HttpException("更新失败");
    }
  }