【问题标题】:I want to save data in my hasura API database using the input field of my react app我想使用我的反应应用程序的输入字段将数据保存在我的 hasura API 数据库中
【发布时间】:2020-02-12 07:35:33
【问题描述】:

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

  }

【问题讨论】:

    标签: reactjs graphql hasura


    【解决方案1】:

    添加书籍和作者的突变将是nested mutation,因为书籍和作者表都是相关的。假设您已经从 books 表到 authors 表创建了一个名为 authorobject relationship,突变将如下所示:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      • 2015-05-10
      • 1970-01-01
      • 2017-11-05
      • 1970-01-01
      • 2011-01-16
      相关资源
      最近更新 更多