【问题标题】:How do i connect two types in GraphQL?如何在 GraphQL 中连接两种类型?
【发布时间】:2020-02-01 02:50:53
【问题描述】:

所以我在 GraphQL 中有两种类型:

article.mdx

---
title: "Post n.1"
category: "Category"
---

Post Content

categories.json

[
  {
    "name": "Category",
    "description": "This is a description",
    "order": 1
  }
]

我想查询我的帖子类型以获得这种结果:

{
 "node": {
   "title": Post n.1
   "category": {
     "name": "Category",
     "description": "This is a description",
     "order": 1
   }
 }
}

我该怎么做?我目前正在使用 GatsbyJS!谢谢。

【问题讨论】:

    标签: graphql schema gatsby


    【解决方案1】:

    这很容易,因为你知道你应该使用 gatsby-transformer-remark 来读取 md 文件,所以对于你应该使用 gatsby-transformer-json 的 json 文件,将它添加到插件下的 gatsby-config.js 文件中。那么你需要查询你的数据,不幸的是我真的不认为你可以按照你的要求合并两个文件来获取数据,但是你可以试试这个

    首先在 gatsby-node.js 文件中,您需要引用您将用于过滤查询数据的变量,将这些字段传递给 context

    exports.createPages = async function({ actions, graphql }) {
      const { data } = await graphql(`
        query {
          allMarkdownRemark {
            edges {
              node {
                fields {
                  slug
                }
              }
            }
          }
        }
      `)
      data.allMarkdownRemark.edges.forEach(edge => {
        const slug = edge.node.fields.slug
        actions.createPage({
          path: slug,
          component: require.resolve(`./src/templates/article.js`),
          context: { category: category},
        })
      })
    }
    

    然后在您的页面查询中,您可以通过 Creating Pages from Data Pro grammatically 阅读更多内容来访问过滤后的查询

    export const pageQuery = graphql`
            query MyQuery($category: String!) {
              allMarkdownRemark(filter: {frontmatter: {category: {eq: $category}}}) {
                edges {
                  node {
                    frontmatter {
                      title
                    }
                  }
                }
              }
              allDataJson(filter: {name: {eq: $category}}) {
                edges {
                  node {
                    nodes {
                      name,
                      description,
                      order
                    }
                  }
                }
              }
            }`
    

    然后访问您可以通过const {allMarkdownRemark , allDataJson} = data访问您的数据

    然后根据您的喜好组合这两个数据

    const item = {node : { title: allMarkdownRemark.edges.node[0].frontmatter }};
    item.node.category = allDataJson.edges.node[0].nodes
    

    请注意,这是假设 edge.node 是一个数组,因此我们需要通过 node[0] 精确计算数据的第一个元素,请检查此方法是否有效。

    json 数据的结构是

    { "nodes": [ {
         "name": "Category",
         "description": "This is a description",
         "order": 1
          } 
       ]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-21
      • 2020-11-09
      • 2018-12-18
      • 2021-09-06
      • 1970-01-01
      • 2021-06-07
      相关资源
      最近更新 更多