微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Mikroorm 检查实体是否被删除

如何解决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
});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。