Prisma如何按关联查询?获取已关注用户发布的帖子
问题原因
- 第一个报错
Unknown arg 'some' in where.author.some:Post和作者User是多对一关联,author字段是单个关联对象而非列表,some/every/none这类列表筛选操作符只能用在一对多/多对多的列表关联字段上,放在author层属于语法位置错误。 - 第二个报错
Unknown arg 'followers' in where.author.followers:移除some后,Prisma会把followers识别为User模型的普通字段,但followers是关联列表字段,必须搭配列表操作符使用,直接写在对象层级无法识别。
前置准备
首先补全Schema中缺失的定义,否则Prisma无法正常生成客户端:
model User { uid String @id @default(uuid()) username String? @db.VarChar(24) @unique followers Follows[] @relation(name: "follower") following Follows[] @relation(name: "following") posts Post[] // 补全User对Post的反向关联 } model Post { id Int @id @default(autoincrement()) name String @db.VarChar(255) author User @relation(fields: [authorId], references: [uid]) authorId String } model Follows { follower User @relation(name: "follower", fields: [followerId], references: [uid]) followerId String following User @relation(name: "following", fields: [followingId], references: [uid]) followingId String @@id([followerId, followingId]) // 显式多对多中间表必须加联合主键 }
正确查询写法
单查询写法(适合数据量较小的场景)
直接走关联筛选,将some操作符放在列表关联字段followers层级:
return prisma.post.findMany({ where: { author: { followers: { some: { followerId: args.userId } } } }, include: { author: { select: { uid: true, username: true // 按需选择需要返回的作者字段,无业务需求不要冗余查询followers关联 } } } })
查询逻辑匹配的关联路径为:Post → 关联作者User → 作者的粉丝关联列表Follows[] → 存在粉丝ID等于当前用户ID的记录,完全符合「筛选已关注用户发布的帖子」的需求。
拆分查询写法(推荐,性能更优)
当用户关注量、帖子量较大时,拆分两次查询的执行效率更高,也更方便后续添加分页、排序逻辑:
// 1. 查询当前用户关注的所有用户ID const followedIds = await prisma.follows.findMany({ where: { followerId: args.userId }, select: { followingId: true } }).then(list => list.map(item => item.followingId)) // 2. 查询关注列表内用户发布的帖子 return prisma.post.findMany({ where: { authorId: { in: followedIds } }, include: { author: { select: { uid: true, username: true } } }, // 可直接加排序、分页参数,例如按发布时间倒序: orderBy: { id: 'desc' }, take: 20, skip: 0 })
内容的提问来源于stack exchange,提问作者HavanaSun
相关产品推荐
相关产品推荐

