GraphQL 如何实现按传入食材数组筛选匹配食谱的查询逻辑
实现按食材数组过滤食谱的完整步骤
步骤1:修改GraphQL Schema,为查询增加过滤参数
原有recipe查询未配置入参,需要新增食材过滤的参数支持:
# 修改后的 schema.gql type Recipe { id: Int title: String! author: String link: String category: String subcategory:String ingredients:[Ingredients] } type Ingredients{ id:Int name:String! quantity:Float! measure:String observation:String } type Query { # 新增可选参数 ingredientNames,接收需要匹配的食材名数组 recipe(ingredientNames: [String!]): [Recipe] ingredient:[Ingredient] }
补充说明:如果业务要求传入完整食材对象而非单纯名称,需要单独定义GraphQL输入类型(输入类型不能和输出类型复用),示例:
# 单独定义输入类型,不能直接复用上面的 Ingredients 输出类型 input IngredientQueryInput { name: String! # 如果需要按食材ID匹配,可补充id字段 } # 对应Query参数调整为:recipe(ingredients: [IngredientQueryInput!]): [Recipe]后续Service逻辑可以从输入对象数组中提取所有name/ID做匹配,核心逻辑一致。
步骤2:实现RecipeService的过滤方法
基于现有Knex查询构造器的使用习惯,核心逻辑是筛选包含所有传入食材的食谱(而非任意匹配单个食材),对应SQL核心为分组+计数匹配:
const db = require('../db') class RecipeService { /** * 根据传入的食材名数组查询符合要求的食谱 * @param {string[]} ingredientNames 需要匹配的食材名数组 * @returns {Promise<object[]>} 符合要求的食谱列表 */ async getRecipeByIngredient(ingredientNames = []) { // 边界处理:未传入过滤参数时返回所有食谱 if (ingredientNames.length === 0) { return await db('Recipe').select('*') } // 核心过滤逻辑 const matchedRecipeIds = await db('Ingredient') // 关联食谱表,适配现有食材通过recipe_id关联食谱的结构 .join('Recipe', 'Ingredient.recipe_id', '=', 'Recipe.id') // 筛选出食材名在传入列表内的记录 .whereIn('Ingredient.name', ingredientNames) // 按食谱ID分组,统计每个食谱下匹配到的不同食材数量 .groupBy('Recipe.id') // 分组计数等于传入食材数组长度的,说明该食谱包含所有传入的食材 .havingRaw('COUNT(DISTINCT Ingredient.name) = ?', [ingredientNames.length]) .select('Recipe.id') // 根据匹配到的ID查询完整食谱信息 return await db('Recipe').whereIn('id', matchedRecipeIds).select('*') } } module.exports = RecipeService
逻辑验证(对应业务示例):
- 传入
['糖']:两个食谱分别匹配到1个符合的食材,计数=1与入参数组长度一致,全部返回- 传入
['糖', '蜂蜜', '面粉']:糖蛋糕匹配到3个食材,计数=3符合要求;丝绒蛋糕仅匹配到1个,计数不匹配被过滤,最终只返回糖蛋糕补充适配:如果表结构是多对多关系(存在食谱-食材中间表),只需把
join部分改为关联中间表即可,分组计数逻辑不变。
步骤3:调整Resolver配置,串联参数传递
首先确保Apollo Server初始化时已经把RecipeService挂载到dataSources上,结构参考:
// Apollo Server 初始化配置示例 const server = new ApolloServer({ typeDefs, resolvers, dataSources: () => ({ RecipeService: new RecipeService(), IngredientService: new IngredientService(), // 原有已挂载的服务 }) })
然后修改原有Query的Resolver,把入参传给Service方法:
const resolvers = { Recipe: { async ingredients(recipe, _, { dataSources }) { // 原有Resolver无需修改,查询单食谱关联食材的逻辑不受影响 return await dataSources.IngredientService.getRecipeIngredients(recipe.id) }, }, Query: { // 修改原有recipe查询,接收入参并调用对应服务方法 recipe: async (_, { ingredientNames }, { dataSources }) => { return await dataSources.RecipeService.getRecipeByIngredient(ingredientNames) }, ingredient: async () => db('Ingredient'), } }
查询调用示例
前端传入过滤参数的GraphQL语句写法:
# 传入多个食材做过滤 query GetCakeRecipes { recipe(ingredientNames: ["糖", "蜂蜜", "面粉"]) { id title category ingredients { name quantity measure } } }
常见边界问题处理
- 食材名大小写不匹配问题:如果数据库中食材名大小写不统一,可把
whereIn替换为不区分大小写的匹配:// 替换原有的whereIn逻辑 .whereRaw('LOWER(Ingredient.name) IN (??)', [ingredientNames.map(name => name.toLowerCase())]) - 重复食材计数问题:使用
COUNT(DISTINCT Ingredient.name)是为了避免同一食谱中重复出现同一种食材(比如多次添加糖)导致计数偏高、匹配错误。
内容的提问来源于stack exchange,提问作者Rudson Rodrigues
相关产品推荐
相关产品推荐

