I have 2 models, Recipe and Ingredient.
Basically I have a search function, where ideally when you search for an ingredient, it will return the recipes that uses said ingredient.
I manage to get the query working with the below. The only problem is, it only returns the ingredients that matches the query. I'd like for it to return all ingredients in the Recipe, if one of the ingredients matches the query. How would I adapt the below to do that?
For example if I search for tomato, I will get recipes with tomatoes win them, but the returned ingredients only includes tomatoes, but not the rest of the ingredients.
const recipes = await Recipe.findAll({
include: {
model: Ingredient,
where: {
name: {
[Op.iLike]: `%${ingredients}%`,
},
},
},
});
Thanks in advance!
You can define two associations from Recipe to Ingredient with different aliases: one alias for filtering and another one for fetching all Ingredients like this:
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
}],
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With