【问题标题】:How to delete many rows typeorm - postgresql & node.js(typescript)如何删除多行 typeorm - postgresql 和 node.js(typescript)
【发布时间】:2020-10-22 00:49:17
【问题描述】:

嗨,朋友们,这是我的函数,它获取了一个 id 数组,我想一次性擦除行而不是在循环中运行,但找不到解决方案。 非常感谢帮助。

async remove(ids: DeleteEmployeeAnswerDTO): Promise<boolean> {
        if (ids.employeeAnswersIds.length) {
            for (const id of ids.employeeAnswersIds) {
                await EmployeeAnswers.delete(id.id);
            }
        }
        return true;
    }

【问题讨论】:

标签: node.js postgresql typescript typeorm


【解决方案1】:

如果您的表有一个 ID 列,那么您应该能够传递 IDs 的数组:

await EmployeeAnswers.delete(ids.employeeAnswersIds);

您还可以在 where 子句中使用 In 指定多个 IDs:

await EmployeeAnswers.delete({ id: In(ids.employeeAnswersIds) });

但是,如果您处理具有复合主键的表,例如在我的情况下,以下示例可能是您的解决方案。我对这个答案并不疯狂,但这是我使用DeleteQueryBuilder (docs) 克服这个问题的方法:

async remove(ids: DeleteEmployeeAnswerDTO): Promise<boolean> {
  if (ids.employeeAnswersIds.length) {
    const deleteQueryBuilder = EmployeeAnswer.createQueryBuilder().delete()

    const idClauses = ids.map((_, index) => `ID = :id${index}`)
    const idClauseVariables = ids.reduce((value: any, id, index) => {
      value[`id${index}`] = id
      return value
    }, {})

    await deleteQueryBuilder.where(idClauses.join(' OR '), idClauseVariables).execute()
  }
  return true;
}

【讨论】:

  • 由于提问者提供的示例明确表示他的实体只有一个主键,因此我将突出显示您提供的最后一个示例。
【解决方案2】:

您可以搜索多条记录,然后删除在单个操作中找到的实体。如果未找到一个或多个实体,则不会删除任何内容。

async removeMany(ids: string[]) {
    const entities = await this.entityRepository.findByIds(ids);
    if (!entities) {
      throw new NotFoundException(`Some Entities not found, no changes applied!`);
    }
    return this.entityRepository.remove(entities);
  }

【讨论】:

  • 这可以工作,但是该过程包含不必要的查询。如果有大量的 id,第一次查询可能会很慢。
  • 是的,但根据我的经验,如果表中不存在提供的 id,则删除或删除会灾难性地失败。服务器只是崩溃......如果你问我,这太疯狂了。您将如何在单个查询中规避此问题?问候
猜你喜欢
  • 2021-01-27
  • 2020-04-29
  • 1970-01-01
  • 2022-08-23
  • 2016-02-15
  • 2021-06-30
  • 2019-12-25
  • 2022-07-18
  • 2015-10-24
相关资源
最近更新 更多