我正在努力学习将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数组的帖子。我需要为每个url创建一个Image记录,并将它们附加到帖子中。
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: ????
},
})
},
})
})
你能帮我弄清楚如何正确地做这件事吗?
- 我不知道如何将json对象数组传递给args。有类似
stringArg()
或intArg()
的东西,但是如何接受数组 - 创建一堆
Image
对象并将它们附加到Post
的正确方法是什么?我应该有一个for循环,然后手动逐个创建它们,然后以某种方式附加它们吗?或者有更好的方法吗
你知道有没有人做这种事的例子吗?
就像nonNull
一样,也有list
类型。您可以使用它并在其中创建arg
。
至于创建图像,您可以使用create
并将图像数组传递给post
,如图所示。
我已经使用extendInputType
完成了这项工作,下面是一个示例
- 首先必须定义反输入
export const saleDetailInput = extendInputType({
type: 'SaleDetailInput',
definition(t) {
t.field(SaleDetail.productId)
}
});
- 定义参数
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) {
},
})
},
})
从nexus中留下一个更详细的例子。不需要创建新的CCD_ 11。它就像下面的arg
示例一样简单。
import { queryType, stringArg, list } from 'nexus'
queryType({
definition(t) {
t.field('tags', {
type: list('String'), // -> [String]
args: {
ids: list(stringArg()) // or list('String') -> [String]
},
resolve() {
// ...
}
})
}
})