【问题标题】:Sequelize query - Return all items, if one item matches querySequelize query - 如果一项匹配查询,则返回所有项目
【发布时间】:2020-09-09 16:52:06
【问题描述】:

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

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

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

例如,如果我搜索西红柿,我会得到带有西红柿的食谱,但返回的成分仅包括西红柿,而不包括其余成分。

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

提前致谢!

【问题讨论】:

    标签: sequelize.js


    【解决方案1】:

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

    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
          }],
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-23
      • 2021-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-02
      • 1970-01-01
      相关资源
      最近更新 更多