首页 > 解决方案 > 如何在 Hasura 中构建多对多插入突变?

问题描述

我正在 Hasura 中构建我的第一个多对多插入突变,但发现它很困难。文档中的语法和随附的解释很难理解。

我只是想在 acomponent和 a之间添加一个连接module

这是我当前查询的状态。

mutation MyMutation {
  insert_component(objects: {component_module: {data: {module: {data: {id: "775c9e27-c974-4cfa-a01f-af50bd742726"}, on_conflict: {constraint: module_id_key, update_columns: id}}}}}) {
    affected_rows
    returning {
      id
      component_modules
    }
  }
}

这是我得到的错误。

{
  "errors": [
    {
      "extensions": {
        "path": "$.selectionSet.insert_component.args.objects[0].component_module.data",
        "code": "constraint-violation"
      },
      "message": "Not-NULL violation. null value in column \"component_id\" violates not-null constraint"
    }
  ]
}

在此先感谢您的帮助。

标签: graphqlhasura

解决方案


您的突变不起作用,因为您手动插入了 id,并且当 Hasura 生成查询时,它在父项中没有 id。

在进行嵌套插入时,最好让 PostgreSQL 为您生成 id。这样,您将能够插入关系的任何一方。

在您的示例中,您实际上并不需要在每个表中都有 component_modules 列。在进行多对多插入时,您可以使用每个表的 id 作为外键。

例如:

component - id - created_at - updated_at - name module - id - created_at - updated_at - name component_module - component_id - module_id

突变应该是这样的:

mutation {
  insert_component(objects: {
    name:"component name",
    component_modules: {
      data: {
        module: {
          data: {
            name: "module name"
          }
        }
      }
    }
  }) {
    returning {
      id
      component_modules {
        component {
          name
        }
      }
    }
  }
}

推荐阅读