根据书籍author_id获取作者数据

时间:2020-01-26 20:35:02

标签: graphql apollo apollo-client apollo-server

我有两个数据库表:

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

typeDefs:

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

但是我如何像这样基于author_id要求带有作者数据的书?

const queryBook = gql`
  query Book($id: ID!) {
    book(id: $id) {
      id
      title
      author_id
      author {
        id
        name
      }
    }
  }
`

1 个答案:

答案 0 :(得分:1)

您应该为书籍的作者编写自定义解析器

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

      .
      .
      .
    }