[英]Graphql query using a variable for one of the arguments
I'm using Gatsby and Graphql to build a website and I'm using the 'createPage' API from Gatsby to create all my pages, sourcing the data from the graphql CMS https://hygraph.com/ .
我可以使用“gatsby-node.js”文件和createPage的“上下文”将动态值传递给我的模板,如下所示:
createPage({
path: `/path-to-my-page',
component: require.resolve(`./src/my-template.js`),
context: {
product_attribute: "metal",
product_attributeValue: "silver"
},
})
当我在我的模板中创建页面查询时,我已经将一个动态值传递给我的模板,“product_attributeValue”和以下代码可以正常工作:
export const pageQuery = graphql`
query ProductListingByAttributeQuery(
$product_attribute: String
$product_attributeValue: String
) {
gcms {
products(
orderBy: updatedAt_DESC
where: {
metal: $product_attributeValue
}
) {
slug
title
image
content
}
}
}
`
但我真正想做的是在“where”中使用“product_attribute”变量,而不是像这样的字符串“metal”:
where: {
$product_attribute: $product_attributeValue
}
但是我收到语法错误,说它不喜欢我在where: {...}
object 中使用$product_attribute
。 错误显示“语法错误:预期名称,找到 $”。
可以在这里做我想做的事吗? 在那我想使用变量'product_attribute'而不是字符串?
我认为您不能在 Gatsby 的保护伞中使用“标准” GraphQL 语法,因为 Gatsby 提供了自己的 GraphQL 实现, where
filter 不是有效的 operator 。 如果您在 GraphiQL 操场上测试查询,它将中断(输出相同的错误消息),因为它不是有效选项。
您正在正确传递上下文值,但以无效的方式使用它们,您可能希望使用filter
以及in
、 ni
、 nin
运算符。 更多参考: https://www.gatsbyjs.com/docs/graphql-reference/
例如:
export const pageQuery = graphql`
query ProductListingByAttributeQuery(
$product_attribute: String
$product_attributeValue: String
) {
gcms(productType: {eq: $product_type}) {
products {
slug
title
image
content
}
}
}
`
注意:这不是复制/粘贴。 它需要调整和完善
像这样的东西应该可以工作,但正如我所说,测试它并使用 GraphiQL 操场(在localhost:8000/___graphql
)构建查询,这真的很有帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.