在GraphQL schema中设置“returning”以确保Apollo在创建对象时返回关联对象。
示例代码:
type Mutation {
createPost(input: CreatePostInput!): Post!
}
type CreatePostInput {
title: String!
content: String!
author_id: ID!
}
type Post {
id: ID!
title: String!
content: String!
author: User!
}
type User {
id: ID!
name: String!
posts: [Post!]!
}
extend type Mutation {
createPost(input: CreatePostInput!): CreatePostPayload
}
type CreatePostPayload {
post: Post!
}
extend type Post {
author: User! @belongsTo
}
extend type User {
posts: [Post!]! @hasMany
}
在上面的例子中,我们使用了@belongsTo
和@hasMany
来建立Post
和User
之间的关联。我们还扩展了Mutation
类型以添加CreatePostPayload
。这可以确保Apollo在创建帖子时返回相关作者对象。
下面是createPost
解析程序的示例代码:
async function createPost(parent, args, context, info) {
const post = await context.prisma.post.create({
data: {
title: args.input.title,
content: args.input.content,
author: { connect: { id: args.input.author_id } },
},
include: { author: true },
})
return { post }
}
我们在提交数据库调用时使用了include
参数,以便Prisma在创建帖子后返回相关作者对象。最后,我们返回了CreatePostPayload
,该对象包含创建的帖子和相关的作者对象。