Prisma查询用户共享列表时include中使用where参数报错如何解决
问题原因
你遇到的报错是因为Prisma对to-one(一对一)类型的关联字段,在include时不支持添加where过滤参数,只有to-many(对多)类型的关联字段才支持在include中使用where筛选子集。
你代码里user_lists和lists是一对一关联,因此include.lists下不允许加where参数,这就是报错提示Unknown arg 'where' in include.lists.where的根本原因。
修正方案
方案1:将过滤条件移到顶层where(推荐)
直接在查询user_lists的顶层where中加入关联字段的过滤规则,筛选同时满足「归属目标用户」和「列表作者不是目标用户」的记录:
const sharedLists = await prisma.user_lists.findMany({ where: { user_id: THE_USERS_ID, lists: { author: { not: THE_USERS_ID } } }, include: { lists: true } });
方案2:从users模型出发查询(逻辑更直观)
如果需要同时返回用户的其他信息,可以从users表入手查询,结构更清晰:
const user = await prisma.users.findUnique({ where: { id: THE_USERS_ID }, include: { lists_owned: { where: { lists: { author: { not: THE_USERS_ID } } }, include: { lists: true } } } }); // 提取共享列表数据:const sharedLists = user?.lists_owned.map(item => item.lists)
小提示
所有Prisma客户端的查询方法都是异步的,需要搭配await或者.then()使用,否则只会拿到Promise对象而非实际查询结果。
内容的提问来源于stack exchange,提问作者Jamie S
相关产品推荐
相关产品推荐

