graphql - 使用GraphQL和Prisma级联删除相关节点

标签 graphql cascading-deletes prisma

我正在尝试找出 GraphQL 中的级联删除。

我正在尝试删除 Question 类型的节点,但 QuestionVote 类型与 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 实例?

如果它很重要,以下是创建 QuestionQuestionVote 的突变:

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,
  )
}

谢谢!

最佳答案

您可以通过修改数据模型来设置级联删除。

鉴于您的问题,我假设您的数据模型看起来有点像这样:

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 节点也会被删除。

Note: If omitting onDelete, the value is automatically set to onDelete: SET_NULL by default. This means that deleting a node results in setting the other side of the relation to null.

您可以阅读有关 Prisma 中级联删除的更多信息 in the documentation .

关于graphql - 使用GraphQL和Prisma级联删除相关节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50497417/

相关文章:

javascript - 如何在打开模态时更新图像src

ruby-on-rails - 如何在Rails ActiveRecord中的one_to_many关系中进行级联删除?

lambda - Netlify 函数无法导入相关的 .graphql 类型定义文件

mysql - hibernate 不会在 mysql 中生成删除级联以映射 HashMap

sql - CASCADE 多对多自引用表中的删除

node.js - 与 Prisma 2 相关的多个过滤器

prisma - 如何使用字典数据创建棱镜迁移?

javascript - GraphQL:不可为空的数组/列表

graphql - 错误: Response not successful: Received status code 400"Graphql

graphql - 枚举可以在 GraphQL 中返回描述(字符串)吗?