序列化查询 - Return 所有项目,如果一个项目匹配查询

Sequelize query - Return all items, if one item matches query

我有 2 个模型,配方和成分。

基本上我有一个搜索功能,理想情况下,当您搜索一种成分时,它会 return 使用该成分的食谱。

我设法使查询与以下内容一起使用。唯一的问题是,它只有 returns 匹配查询的成分。如果其中一种成分与查询匹配,我希望它 return 食谱中的所有成分。我将如何调整以下内容来做到这一点?

例如,如果我搜索番茄,我会得到含有番茄的食谱,但 returned 的成分只包括番茄,而不包括其他成分。

const recipes = await Recipe.findAll({
      include: {
        model: Ingredient,
        where: {
          name: {
            [Op.iLike]: `%${ingredients}%`,
          },
        },
      },
});

提前致谢!

您可以使用不同的别名定义从食谱到成分的两个关联:一个用于过滤的别名,另一个用于获取所有成分的别名,如下所示:

Recipe.hasMany(Ingredient, { foreignKey: 'recipeId', as: 'Ingredients' })
Recipe.hasMany(Ingredient, { foreignKey: 'recipeId', as: 'FilteringIngredients' })
...
const recipes = await Recipe.findAll({
      include: [{
        model: Ingredient,
        as: 'FilteringIngredients',
        where: {
          name: {
            [Op.iLike]: `%${ingredients}%`,
          },
        },
      }, {
        model: Ingredient,
        as: 'Ingredients',
        separate: true
      }],
});

我必须使用与@Anatoly 提供的相同的技巧,而且效果很好!

问题是,它也是 returns 一个字段 FilteringIngredients,其中包含匹配的元素。对于那些想从返回的对象中删除这个字段的人,可以添加一个 attributes: [] 如下:

await Recipe.findAll({
  include: [{
    model: Ingredient,
    as: "FilteringIngredients",
    where: { /* my where clause */ },
    attributes: [],
  },
  {
    model: Ingredient,
    as: "Ingredients",
    separate: true,
  }]
})