1

em.nativeDelete 返回删除了多少实体,所以我可以这样做:

const count = await this.em.nativeDelete(User, {id});

if(!count){
    throw new EntitiyNotFoundException(`User with id: ${id} is not found`);
}

有没有办法用 remove() 做同样的事情。它返回 EntityManager 我如何检查是否删除了实体:

const user = this.em.getReference(User, id);
await this.em.remove(user); 
4

1 回答 1

2

由于em.remove()您首先需要加载实体以查看它是否存在,因此无法从 UoW 访问已删除的计数,因为刷新不绑定到该特定查询,它可以包含针对许多不同实体/表和操作的许多查询(克鲁德)。

您想在显式事务中执行此操作,以确保其他请求不会删除您刚刚从数据库中检索到的记录。

await em.transactional(async em => {
  // this will throw if not found, you might want to use `em.findOne` and 
throw yourself
  const user = await em.findOneOrFail(User, id);
  em.remove(user); // flush will be called automatically when using explicit transactions
});
于 2021-07-19T09:54:30.967 回答