1

我正在尝试学习一起使用 Prisma 和 Nexus。我希望有经验的人可以帮助我。

我想创建一个附有几张图片的帖子。

我的 Prisma 模型如下所示:

model Post {
  id String @id @default(cuid())
  title String
  body String
  images Image[] @relation("ImagePost")
}

model Image {
  id String @id @default(cuid())
  post Post @relation("ImagePost", fields: [postId], references: [id])
  postId String
  name String
  url String
}

我需要编写一个 Nexus 突变,它可以接受带有标题、正文和图像 url 数组的帖子。我需要为每个网址创建一个图像记录,并将它们附加到帖子中。

const Mutation = objectType({
  name: 'Mutation',
  definition(t) {
    t.field('createPost', {
      type: 'Post',
      args: {
        title: nonNull(stringArg()),
        body: stringArg(),
        images: ????
      },
      resolve: (_, args, context: Context) => {
        return context.prisma.post.create({
          data: {
            title: args.title,
            body: args.body,
            images: ????
          },
        })
      },
    })
})

你能帮我弄清楚如何正确地做到这一点吗?

  1. 我不知道如何将 json 对象数组传递给 args。有类似stringArg()or的东西intArg(),但是你如何接受一个数组?
  2. 创建一堆Image对象并将它们附加到的正确方法是Post什么?我应该有一个 for 循环并手动创建它们,然后以某种方式附加它们吗?或者,还有更好的方法?

你知道有没有人做这种事情的例子?

4

2 回答 2

0

就像nonNull还有一种list类型一样。您可以使用它并在其中创建一个arg

至于创建图像,您可以使用create图像数组并将其传递给,post如下所示

于 2021-06-18T07:11:56.113 回答
0

我已经使用了extendInputType,这里有一个例子

  1. 首先,您必须定义 de 输入
export const saleDetailInput = extendInputType({
  type: 'SaleDetailInput',
  definition(t) {
    t.field(SaleDetail.productId)
  }
});
  1. 定义参数
export const createSale = extendType({
  type: 'Mutation',
  definition(t) {
    t.nonNull.list.field('createSale', {
      type: 'Sale',
      args: {
        total: nonNull(floatArg()),
        customerId: nonNull(intArg()),
        products: nonNull(list(nonNull('SaleDetailInput'))),
      },
      async resolve(parent, { products, ...others }, context) {
      },
    })
  },
})
于 2021-11-12T23:10:44.130 回答