You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用GraphQL查询返回的动态ID作为参数查询对应项目数据

解决方案

最优实现方案(无需拆分查询)

你当前的需求完全可以通过GraphQL嵌套关联字段实现,不需要拆分两个查询,Sanity的GraphQL接口原生支持解析引用字段的关联数据,直接修改查询语句即可:

export const query = graphql`
  query myQuery {
    allSanityFrontpage {
      nodes {
        content {
          ... on SanityHero {
            _key
            _type
            heroIntro
            heroHeader
            heroButtonText
            heroProjectReference {
              id
              title
              slug {
                current
              }
              # 直接在这里添加你需要的项目字段即可,无需单独查询sanityProject
              coverImage {
                asset {
                  title
                  fluid(maxWidth: 800) {
                    ...GatsbySanityImageFluid
                  }
                }
              }
            }
          }
        }
      }
    }
  }
`;

该方案无需手动传递ID,在CMS修改关联项目后,重新构建就能自动拉取最新对应项目的数据,完全替代硬编码ID的实现。

特殊场景下拆分查询的实现方式

如果确实有业务需求必须拆分两次查询,可根据场景选择对应实现:

  • 构建时页面动态查询(Gatsby场景)
    首先在gatsby-node.js的createPages钩子中先执行首次查询拿到hero关联的项目ID,将ID作为页面上下文参数传递:
    exports.createPages = async ({ graphql, actions }) => {
      const { createPage } = actions
      const result = await graphql(`
        query {
          allSanityFrontpage {
            nodes {
              content {
                ... on SanityHero {
                  heroProjectReference {
                    id
                  }
                }
              }
            }
          }
        }
      `)
      const projectId = result.data.allSanityFrontpage.nodes[0].content.find(item => item._type === 'SanityHero').heroProjectReference.id
      createPage({
        path: '/',
        component: require.resolve('./src/pages/index.js'),
        context: {
          projectId: projectId
        }
      })
    }
    
    页面中的查询就可以接收上下文参数动态查询:
    export const query = graphql`
      query myQuery($projectId: String!) {
        allSanityFrontpage {
          nodes {
            content {
              ... on SanityHero {
                _key
                _type
                heroIntro
                heroHeader
                heroButtonText
                heroProjectReference {
                  id
                  title
                  slug {
                    current
                  }
                }
              }
            }
          }
        }
        sanityProject(id: { eq: $projectId }) {
          id
          title
          coverImage {
            asset {
              title
              fluid(maxWidth: 800) {
                ...GatsbySanityImageFluid
              }
            }
          }
        }
      }
    `
    
  • 客户端运行时查询
    如果是运行时需要动态拉取数据,使用GraphQL客户端(如Apollo Client)先执行第一个查询拿到ID,再将ID作为变量传入第二个查询的请求参数即可。

内容的提问来源于stack exchange,提问作者Hellodan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 13:24:05