Prisma2 错误:“prisma.post.create()”调用无效:PostUncheckedCreateInput 类型的 data.tags 中的参数“tags”未知

Ray*_*lez 6 nexus graphql prisma nexus-prisma prisma2

我想创建一个带有附加标签列表的帖子。这些模型是多对多连接的(一个帖子可以有多个标签,一个标签可以有多个帖子)。

这是我的棱镜模型:

model Post {
  id String @id @default(cuid())
  slug String @unique
  title String
  body String
  tags Tag[]
}

model Tag {
  id String @id @default(cuid())
  posts Post[]
  name String
  slug String @unique
}
Run Code Online (Sandbox Code Playgroud)

这是一个突变,我试图创建一个帖子,并为其附加标签:

t.field('createPost', {
  type: 'Post',
  args: {
    title: nonNull(stringArg()),
    body: stringArg(),
    tags: list(arg({ type: 'TagInput' }))
  },
  resolve: async (_, args, context: Context) => {
    // Create tags if they don't exist
    const tags = await Promise.all(
      args.tags.map((tag) =>
        context.prisma.tag.upsert({
          create: omit(tag, "id"),
          update: tag,
          where: { id: tag.id || "" },
        })
      )
    )
    return context.prisma.post.create({
      data: {
        title: args.title,
        body: args.body,
        slug: `${slugify(args.title)}-${cuid()}`,
        // Trying to connect a post to an already existing tag
        // Without the "tags: {...} everything works
        tags: {
          set: [{id:"ckql6n0i40000of9yzi6d8bv5"}]
        },
        authorId: getUserId(context),
        published: true, // make it false once Edit post works.
      },
    })
  },
})
Run Code Online (Sandbox Code Playgroud)

这似乎不起作用。

我收到错误:

Invalid `prisma.post.create()` invocation:
{
  data: {
    title: 'Post with tags',
    body: 'Post with tags body',
    slug: 'Post-with-tags-ckql7jy850003uz9y8xri51zf',
    tags: {
      connect: [
        {
          id: 'ckql6n0i40000of9yzi6d8bv5'
        }
      ]
    },
  }
}
Unknown arg `tags` in data.tags for type PostUncheckedCreateInput. Available args:
type PostUncheckedCreateInput {
  id?: String
  title: String
  body: String
  slug: String
}
Run Code Online (Sandbox Code Playgroud)

tags帖子上的字段好像不见了?但我确实跑prisma generate了并且prisma migrate. 此外,如果我使用 Prisma Studio 手动添加标签,我可以成功查询帖子上的标签。什么可能导致此问题?

Rya*_*yan 1

您也需要使用connectfor 。author因此,以下内容将正常工作:

return context.prisma.post.create({
      data: {
        title: args.title,
        body: args.body,
        slug: `${slugify(args.title)}-${cuid()}`,
        // Trying to connect a post to an already existing tag
        // Without the "tags: {...} everything works
        tags: {
          set: [{id:"ckql6n0i40000of9yzi6d8bv5"}]
        },
        author: { connect: { id: getUserId(context) } },
        published: true, // make it false once Edit post works.
      },
})
Run Code Online (Sandbox Code Playgroud)