我想使用react应用程序的输入字段将数据保存在hasura API数据库中

时间:2019-10-15 15:07:13

标签: reactjs graphql hasura

我的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>
  );

  }

1 个答案:

答案 0 :(得分:0)

由于书和作者表都相关,因此添加书和作者的变异将是nested mutation。假设您已经从books表到authors表创建了一个名为object relationship的{​​{1}},则该突变看起来像这样:

author

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

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