基于Post ID与所属User ID更新Post遇Prisma查询错误,求解决方案
问题解决方法
错误原因分析
findUnique仅支持通过唯一标识字段(如id)查询,不允许添加额外条件(比如嵌套的author),因为PostWhereUniqueInput类型只定义了id作为唯一查询参数。- 后续的
post.update方法缺少where条件,无法定位要更新的Post。
方案一:原子更新(推荐)
直接在update操作中同时指定id和authorId条件,既保证数据一致性,又避免额外查询:
updatePost: async (parent, args, context) => { const { userId } = context; try { const updatedPost = await context.prisma.post.update({ where: { id: args.id, // 假设Post表有直接关联author的字段authorId(从关联关系推断) authorId: userId }, data: { ...args.data } }); return updatedPost; } catch (error) { // 捕获Prisma找不到数据的错误,统一返回提示 throw new Error('post not found'); } },
方案二:先查询验证再更新
如果需要单独校验Post存在性,改用findFirst支持多条件查询,再执行更新:
updatePost: async (parent, args, context) => { const { userId } = context; const postExist = await context.prisma.post.findFirst({ where: { id: args.id, author: { id: userId } } }); if (!postExist) { throw new Error('post not found'); } const updatedPost = await context.prisma.post.update({ where: { id: args.id }, data: { ...args.data } }); return updatedPost; },
关键说明
- 方案一利用Prisma的原子更新特性,避免了先查询再更新的竞态问题(比如查询后Post被其他操作修改)。
- 确保你的Prisma Schema中,Post模型包含
authorId字段(与User表的关联外键),这样才能直接在where中使用authorId: userId;如果Schema是通过嵌套关联定义的,findFirst的嵌套查询方式依然有效。
内容的提问来源于stack exchange,提问作者amgoun
相关产品推荐
相关产品推荐

