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

Prisma中使用findMany查询多对多关联是否存在的最优实现方式

Prisma + Postgres 查询帖子列表带当前用户点赞状态最优方案

最优方案(单SQL查询,性能最佳)

该方案通过Postgres的EXISTS子查询实现,全程仅发起1次数据库请求,无额外内存计算开销,是大数据量场景下的最优选择。

你需要先拿到当前登录用户的ID(示例中记为currentUserId),查询代码如下:

import { PrismaClient, sql } from '@prisma/client'
const prisma = new PrismaClient()

// 此处替换为实际当前登录用户的ID
const currentUserId = "xxx"

const posts = await prisma.post.findMany({
  select: {
    id: true,
    content: true,
    isLiked: sql<boolean>`
      EXISTS (
        SELECT 1 FROM "_postlikes" 
        WHERE "A" = "Post".id AND "B" = ${currentUserId}
      )
    `.as('is_liked')
  }
})

注意:如果你显式定义了多对多中间表,把上面SQL里的表名和字段替换为你自定义的中间表对应字段即可。

返回结果直接符合要求的格式,无需二次处理。


备选方案(无Raw SQL,类型更友好)

如果你不想手写原生SQL,可以用关联查询后二次映射的方案,性能略低于最优方案,但类型提示更完整,适合小数据量场景:

const currentUserId = "xxx"

const rawPosts = await prisma.post.findMany({
  select: {
    id: true,
    content: true,
    likes: {
      where: { id: currentUserId },
      select: { id: true }
    }
  }
})

// 映射得到最终结果
const posts = rawPosts.map(post => ({
  id: post.id,
  content: post.content,
  isLiked: post.likes.length > 0
}))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 02:24:05