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

Prisma多对多关联中upload.posts被标记为never类型问题求助

问题原因及解决方法

你犯了个核心错误:findFirst是查询数据的方法,而connect是用来更新关联关系的写操作,这俩不能混在同一个查询里用,所以Prisma才会提示posts的类型是never——因为查询操作的配置里根本不支持connect这个字段。

正确操作分两种场景:

场景1:查询某个Upload,同时获取它关联的Posts

如果是要查询数据,应该用include或者select来关联查询Posts,代码如下:

const uploadWithPosts = await prisma.upload.findFirst({
  where: {
    id: upload.id,
  },
  select: {
    type: true,
    // 用select指定要查询的Posts字段
    posts: {
      select: {
        id: true,
        // 其他你需要的Post字段
      }
    }
  },
});

或者用include直接包含整个Posts对象:

const uploadWithPosts = await prisma.upload.findFirst({
  where: {
    id: upload.id,
  },
  include: {
    posts: true, // 包含所有关联的Posts
  },
});

场景2:给已有的Upload关联一个Post

如果是要建立关联(也就是你代码里想做的connect操作),应该用update方法,而不是findFirst:

const updatedUpload = await prisma.upload.update({
  where: {
    id: upload.id,
  },
  data: {
    posts: {
      connect: {
        id: post.id,
      },
    },
  },
  // 可以加上include/select来返回更新后的关联数据
  include: {
    posts: true,
  },
});

另外补充:你的Schema定义的是隐式多对多关联,Prisma会自动生成中间表,这个是没问题的,不需要手动创建中间表,只要操作方法对应正确就行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 05:16:38