Reputation: 161
I'm trying to create dynamic where clause to filter data using sequelize. But I am stuck in using "OR" in where clause.
I have tried given below way to create dynamic where clause
let where = {};
if(obj.NoteCat)
where.NoteCat = obj.NoteCat;
if(obj.NoteSubCat)
where.NoteSubCat = obj.NoteSubCat;
where.NoteEntryDate = {
[Op.and]: {
[Op.gte]: obj.FromDate,
[Op.lte]: obj.ToDate,
}
};
where.NoteWeekEndingDate = {
[Op.and]: {
[Op.gte]: obj.FromDate,
[Op.lte]: obj.ToDate,
}
};
await table.findAll({
where: where,
}
I expect given below query
SELECT *
FROM table
WHERE NoteCat = ''
AND NoteSubCat = ''
OR (NoteEntryDate >= '2019-05-16 12:52:50.931' AND NoteEntryDate <= '2019-05-16 12:52:50.931')
OR (NoteWeekEndingDate >= '2019-05-16 12:52:50.931' AND NoteWeekEndingDate <= '2019-05-16 12:52:50.931')
But the actual output is
SELECT *
FROM table
WHERE NoteCat = ''
AND NoteSubCat = ''
AND (NoteEntryDate >= '2019-05-16 12:52:50.931' AND NoteEntryDate <= '2019-05-16 12:52:50.931')
AND (NoteWeekEndingDate >= '2019-05-16 12:52:50.931' AND NoteWeekEndingDate <= '2019-05-16 12:52:50.931')
How I get expected result. I have already wasted my whole day. Any help in this regard is highly appreciated.
Thanks.
Upvotes: 6
Views: 10283
Reputation: 1626
You can create it in a reverse order, like so:
let where = {
[Op.or]: {
NoteEntryDate: {
[Op.and]: {
[Op.gte]: obj.FromDate,
[Op.lte]: obj.ToDate,
}
},
NoteWeekEndingDate: {
[Op.and]: {
[Op.gte]: obj.FromDate,
[Op.lte]: obj.ToDate,
}
}
}
};
if(obj.NoteCat)
where.NoteCat = obj.NoteCat;
if(obj.NoteSubCat)
where.NoteSubCat = obj.NoteSubCat;
await table.findAll({
where: where,
}
Upvotes: 6