我正试图找出GraphQL中的级联删除。
我正在尝试删除Question
类型的节点,但类型QuestionVote
与Question
具有必需的关系。我正在寻找一种方法来同时删除Question
及其所有选票。
删除Question
的变异:
type Mutation {
deleteQuestion(where: QuestionWhereUniqueInput!): Question!
}
它的解析器(我正在使用Prisma):
function deleteQuestion(parent, args, context, info) {
const userId = getUserId(context)
return context.db.mutation.deleteQuestion(
{
where: {id: args.id}
},
info,
)
}
如何修改该突变以删除相关的QuestionVote
个节点?或者我应该添加一个单独的突变来删除QuestionVote
的一个或多个实例?
如果重要,以下是创建Question
和QuestionVote
的突变:
function createQuestion(parent, args, context, info) {
const userId = getUserId(context)
return context.db.mutation.createQuestion(
{
data: {
content: args.content,
postedBy: { connect: { id: userId } },
},
},
info,
)
}
async function voteOnQuestion(parent, args, context, info) {
const userId = getUserId(context)
const questionExists = await context.db.exists.QuestionVote({
user: { id: userId },
question: { id: args.questionId },
})
if (questionExists) {
throw new Error(`Already voted for question: ${args.questionId}`)
}
return context.db.mutation.createQuestionVote(
{
data: {
user: { connect: { id: userId } },
question: { connect: { id: args.questionId } },
},
},
info,
)
}
谢谢!
答案 0 :(得分:4)
您可以通过修改数据模型来设置级联删除。
考虑到你的问题,我认为你的数据模型看起来有点像这样:
type Question {
id: ID! @unique
votes: [QuestionVote!]! @relation(name: "QuestionVotes")
text: String!
}
type QuestionVote {
id: ID! @unique
question: Question @relation(name: "QuestionVotes")
isUpvote: Boolean!
}
然后你必须将onCascade: DELETE
字段添加到@relation
指令中,如下所示:
type Question {
id: ID! @unique
votes: [QuestionVote!]! @relation(name: "QuestionVotes" onDelete: CASCADE)
text: String!
}
type QuestionVote {
id: ID! @unique
question: Question @relation(name: "QuestionVotes")
isUpvote: Boolean!
}
现在,每次删除Question
节点时,所有相关的QuestionVote
节点也会被删除。
注意:如果省略
onDelete
,默认情况下该值会自动设置为onDelete: SET_NULL
。这意味着删除节点会导致将关系的另一面设置为null
。
您可以在Prisma in the documentation中阅读有关级联删除的更多信息。