如何通过ShopifyAPI::GraphQL按ID及筛选条件获取产品与集合
我来帮你把这两个Shopify REST接口的功能转换成GraphQL实现,结合你给出的shopify_api GraphQL客户端示例,直接看下面的代码就一目了然:
1. 按产品ID批量获取产品
对应你原来的REST调用(批量指定产品ID、分页获取,每页最多250条),GraphQL可以通过products查询,用ids过滤条件加上分页参数first来实现:
# 激活session后初始化GraphQL客户端 client = ShopifyAPI::GraphQL.new # 定义查询:按指定ID批量获取产品,支持分页(这里first设为250对应原limit) PRODUCTS_BY_IDS_QUERY = client.parse <<-'GRAPHQL' query GetProductsByIds($productIds: [ID!]!, $first: Int!, $after: String) { products(ids: $productIds, first: $first, after: $after) { edges { node { id title # 这里可以添加你需要的其他产品字段 } cursor # 用于下一页分页 } pageInfo { hasNextPage } } } GRAPHQL # 执行查询,传入参数:产品ID数组、每页数量、分页游标(首次传nil) result = client.query(PRODUCTS_BY_IDS_QUERY, variables: { productIds: product_ids.map { |id| "gid://shopify/Product/#{id}" }, # GraphQL需要全局ID格式 first: 250, after: nil }) # 处理返回结果 products = result.data.products.edges.map(&:node) next_page_cursor = result.data.products.pageInfo.hasNextPage ? result.data.products.edges.last.cursor : nil
注意:Shopify GraphQL的ID是全局ID(gid格式),所以需要把原来的数字ID转换成
gid://shopify/Product/[数字ID]的格式。如果你的product_ids已经是全局ID,就可以直接传入。
2. 按产品ID筛选并获取关联的集合ID
对应原来的REST调用(获取指定产品关联的所有Collect的collection_id),GraphQL可以通过两种方式实现:
方式一:通过collects查询(和原REST逻辑最匹配)
client = ShopifyAPI::GraphQL.new # 定义查询:获取指定产品关联的所有集合ID COLLECTIONS_BY_PRODUCT_ID_QUERY = client.parse <<-'GRAPHQL' query GetCollectionsByProductId($productId: ID!, $first: Int!, $after: String) { collects(first: $first, after: $after, query: "product_id:#{productId}") { edges { node { collection { id # 对应原REST的collection_id } } cursor } pageInfo { hasNextPage } } } GRAPHQL # 执行查询,注意productId需要转成全局ID格式 result = client.query(COLLECTIONS_BY_PRODUCT_ID_QUERY, variables: { productId: "gid://shopify/Product/#{product_id}", first: 250, # 同样支持分页,按需调整 after: nil }) # 提取所有关联的集合ID(转成数字ID的话可以拆分gid) collection_ids = result.data.collects.edges.map do |edge| edge.node.collection.id.split('/').last end
方式二:通过product查询直接获取关联集合(写法更简洁)
如果你只需要获取产品直接关联的集合,这种方式更直观:
client = ShopifyAPI::GraphQL.new PRODUCT_COLLECTIONS_QUERY = client.parse <<-'GRAPHQL' query GetProductCollections($productId: ID!) { product(id: $productId) { collections(first: 250) { edges { node { id } } } } } GRAPHQL result = client.query(PRODUCT_COLLECTIONS_QUERY, variables: { productId: "gid://shopify/Product/#{product_id}" }) collection_ids = result.data.product.collections.edges.map { |e| e.node.id.split('/').last }
提示:确保你使用的
shopify_apiGem版本支持GraphQL功能,直接通过RubyGems安装最新版即可。
内容的提问来源于stack exchange,提问作者aldrien.h
相关产品推荐
相关产品推荐

