Mikroorm 检查实体是否被删除

问题描述

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); 

解决方法

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

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

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
});