1

我的 Hasura API 数据库中有 2 个表,books(id,name,authorId) 和 authors(id,name)。我想通过前端的输入字段在这些表中插入数据。

我有以下突变,但我不知道如何在我的前端定义架构,以便将数据保存在 Hasura API 表中

const ADD_BOOK = gql`
  mutation AddBook($type: String!) {
    addBook(type: $type) {
      name
    }
  }
`;
const ADD_AUTHOR = gql`
  mutation AddAuthor($type: String!) {
    addAuthor(type: $type) {
      name
    }
  }
`;

这是输入表单

function Form(){

  let book,author;
  return (
    <Mutation mutation={ADD_BOOK}>
      {(addBook, { data }) => (        
        <Mutation mutation={ADD_AUTHOR}>
          {(addAuthor, { data }) => (
            <div>
              <form
                onSubmit={e => {
                  e.preventDefault();
                  addBook({ variables: { type: book.value } });
                  addAuthor({ variables: { type: author.value } });
                  book.value = "";
                  author.value = "";
                }}
              >
                <input
                  ref={node => {
                    book = node;
                  }}
                />
                <input
                  ref={node => {
                    author = node;
                  }}
                />
                <button type="submit">Add Item</button>
              </form>
            </div>
          )}
        </Mutation>
      )}
    </Mutation>
  );

  }
4

1 回答 1

1

添加书籍和作者的突变将是嵌套突变,因为书籍和作者表都是相关的。假设您已经创建了一个从书表到作者表的object relationship调用author,突变将如下所示:

const ADD_BOOK_WITH_AUTHOR = gql`
  mutation addBookWithAuthor($bookName: String!, $authorName: String!) {
    insert_books(objects: {
      name: $bookName, 
      author: {
        data: {
          name: $authorName
        }
      }
    }) {
      affected_rows
    }
  }
`;

在您的表格中,您将使用适当的变量调用突变

addBook({ variables: { bookName: book.value, authorName: author.value } });
于 2019-10-17T07:48:44.103 回答