我从PARAMS获得数组中的ID,我应该更新具有特定ID的记录的凭据.问题是,如果没有找到记录,则事务应该回滚.这就是我所做的:
await this.prisma.$transaction( async () => {
for(let id of ids) {
// get category from db
const category = await this.prisma.category.findFirst({
where: { id: +id, deleted_at: null },
});
// check if exists
if (!category) {
throw new BadRequestException({
status: 400,
error: true,
message: 'Category is not found',
});
}
// soft delete from db
await this.prisma.category.update({
where: { id: +id },
data: { deleted_at: new Date() },
});
}
})
即使我在找不到记录时抛出Error,其他记录也会被更新.
我做的第二种方式是:
await this.prisma.$transaction(
ids.map(id => this.prisma.category.update({
where: { id: +id },
data: { deleted_at: new Date() },
})
));
在这种情况下,如果没有找到记录,我会得到这样的错误:
无效的
this.prisma.category.update()
Invoocation in\n/files/src/category/category.service.ts:177:46\n\n 174}\n 175\n 176正在等待this.prisma.$Transaction(\n→177 ids.map(id=>;this.prisma.Category y.UPDATE)(\n操作失败,因为它依赖于一个或多个所需但未找到的记录.找不到要更新的记录
但在这种情况下,其他记录也在更新! 在这种情况下我应该怎么做?
如有任何帮助,我们不胜感激:)