代码之家  ›  专栏  ›  技术社区  ›  ZiiMakc

根据图书作者的id获取作者数据

  •  0
  • ZiiMakc  · 技术社区  · 6 年前

    books: id | title | author_id
    authors: id | name
    

    类型定义:

    const typeDefs = gql`
      type Author {
        id: ID!
        name: String!
      }
    
      type Book {
        id: ID!
        title: String!
        author_id: String!
        author: Author!
      }
    
      type Query {
        book(id: ID!): Book
        author(id: ID!): Author
      }
    `
    

    const resolvers = {
      Query: {
        async book(parent, args) {
          const dbRes = await query('SELECT id, title, author_id FROM books WHERE id=$1', [args.id])
    
          return dbRes[0]
        },
        async author(parent, args) {
          const dbRes = await query('SELECT id, name FROM authors WHERE id=$1', [args.id])
    
          return dbRes[0]
        }
      }
    }
    

    我可以请求获取图书:

    const queryBook = gql`
      query Book($id: ID!) {
        book(id: $id) {
          id
          title
          author_id
        }
      }
    `
    const { data } = useQuery(queryBook, { variables: { id: 1 } })
    

    const queryBook = gql`
      query Book($id: ID!) {
        book(id: $id) {
          id
          title
          author_id
          author {
            id
            name
          }
        }
      }
    `
    
    0 回复  |  直到 6 年前
        1
  •  1
  •   Alex    6 年前

    你应该为一本书的作者编写一个自定义解析器

      const resolvers = {
           Book: {
              author: (parent) => {
                       console.log(parent.author_id)
                return (from database or any where....);
              },
            },
    
          .
          .
          .
        }