My problem in nutshell: I want to use the AND operation in a joined table. I think it is a very general use-case in the real life, but I didn't find any related article, blog, or issue yet. (My bad I think :D)
Let me describe an example of what I mean: I would like to create a webshop and I have a Mobile and a Feature model and there is many-to-many relation between them. There is a multi-select filter for the feature (on my website) and I want to list those mobiles which have selected features. (eg.: A and B and C ...) I think I cannot create it one query because a column cannot be A and B at the same time, but I'm not sure. Example:
const mobiles = await models.mobile.findAll({
where: '???',
attributes: ['id', 'name'],
include: [
{
model: models.feature,
where: '???',
attributes: ['id', 'name],
through: {
attributes: [],
},
},
],
});
I'm interested in the Sequelize and also the SQL solution too.
Example models and expected result:
const Mobile = sequelize.define('Mobile', {
id: {
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER,
},
name: {
type: DataTypes.STRING
}
}, {});
const Feature = sequelize.define('Feature', {
id: {
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER,
},
name: {
type: DataTypes.STRING
}
}, {});
Mobile.belongsToMany(Feature, { through: 'MobileFeature' });
Feature.belongsToMany(Mobile, { through: 'MobileFeature' });
// Example Data in DB (from mobile context)
const exampleData = [
{
"id": 1,
"name": "Mobile1",
"features": [
{
"id": 1,
"name": "A",
},
{
"id": 2,
"name": "B",
},
{
"id": 3,
"name": "C",
},
],
},
{
"id": 2,
"name": "Mobile2",
"features": [],
},
{
"id": 3,
"name": "Mobile3",
"features": [
{
"id": 1,
"name": "A",
},
]
}
];
// Expected result
// Scenario: I want to list those mobiles which have A and C feature
const result = [
{
"id": 1,
"name": "Mobile1",
"features": [
{
"id": 1,
"name": "A",
},
{
"id": 2,
"name": "B",
},
{
"id": 3,
"name": "C",
},
]
},
];