I’m trying to filter products by their attributes that are in the linking table
Product => product_has_attribute => Attribute
I was only able to do OR, but I need to make a more precise filter.
Thanks for any hint!
ps: just replace or with and – doesn’t work)
const category = await CategoryDB.findByPk(category_id);
const products = await category.getProducts({
offset: parseInt(offset, 10),
limit: parseInt(limit, 10),
where: {
...whereClause,
},
order: [["createdAt", "DESC"]],
include: [
{
model: AttributesDB,
where: {
id: {
[Op.or]: [1, 2],
},
},
through: {
where: {
value_ua: { [Op.or]: ["Коричневий", "Середній"] },
},
attributes: ["value_ru", "value_ua"],
},
attributes: ["id", "title_ru", "title_ua", "type"],
},
],
logging: customLogger,
});
SELECT p.*
FROM Products p
JOIN product_has_attributes pha1 ON p.id = pha1.product_id
JOIN Attributes a1 ON pha1.attribute_id = a1.id
JOIN product_has_attributes pha2 ON p.id = pha2.product_id
JOIN Attributes a2 ON pha2.attribute_id = a2.id
WHERE a1.id = 1 AND pha1.value_ua = 'Коричневий'
AND a2.id = 2 AND pha2.value_ua = 'Середній'
2
Answers
It’s hard to tell without some sample data, but, if I got it right, It could be something like this:
You should put your conditions in the joins’ ON clauses in a way that your product ID is joined to both attributes of interest (1 and 2) and each attribute has a value that satisfies condition – 1-Brown, 2-Average. Try it like below:
See the fiddle here.