You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MikroORM使用remove()方法时如何判断实体是否成功删除

MikroORM中使用remove()实现删除校验的方法

em.remove() 是在 UnitOfWork 层面标记实体待删除,真正的数据库删除操作要调用 flush() 才会执行,你可以通过两种方式实现和 nativeDelete() 一致的存在性校验:


方案1:先查询再删除(最直观)

先查询实体是否存在,不存在直接抛出异常,确认存在后再执行删除,逻辑和你现有的 nativeDelete() 校验完全对齐:

const user = await this.em.findOne(User, id);
if (!user) {
  throw new EntityNotFoundException(`User with id: ${id} is not found`);
}
// 标记删除后提交事务到数据库
await this.em.remove(user).flush();

该方案的优势是逻辑清晰,还可以在删除前插入权限校验、关联资源校验等额外逻辑。


方案2:使用getReference + 校验删除结果

如果你不想多执行一次查询,可以继续使用getReference创建代理实体,通过两种方式判断是否删除成功:

方式A:全局配置开启不存在实体删除报错

在MikroORM全局配置中开启removeNotFoundEntities: true,此时flush时如果删除的代理实体不存在,ORM会自动抛出EntityNotFoundError,捕获后处理即可:

try {
  const user = this.em.getReference(User, id);
  await this.em.remove(user).flush();
} catch (e) {
  if (e instanceof EntityNotFoundError) {
    throw new EntityNotFoundException(`User with id: ${id} is not found`);
  }
  // 其他异常按需处理后抛出
  throw e;
}

方式B:手动校验删除影响行数

如果不想全局开启上述配置,可以读取flush返回结果中的删除影响行数判断:

const user = this.em.getReference(User, id);
this.em.remove(user);
const flushResult = await this.em.flush();
const deletedCount = flushResult.affectedRows?.delete ?? 0;
if (!deletedCount) {
  throw new EntityNotFoundException(`User with id: ${id} is not found`);
}

注意:你提供的示例代码漏了flush()调用,只执行em.remove()不会触发真实的数据库删除操作。

内容的提问来源于stack exchange,提问作者ivaylo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 09:27:00