I have a database of articles with several columns and would like to be able to search both title
and description
.
Currently, I have:
JavaScript
x
6
1
Article.findAll({
2
where: {
3
title: { like: '%' + searchQuery + '%' }
4
}
5
});
6
How can I also search the description as well?
I’ve read through the sequelize documentation, even in the Complex filtering / OR / NOT queries
section, but the examples only seem to explain searching in one column.
Advertisement
Answer
Sequelize >= 4.12
JavaScript
1
8
1
const Op = Sequelize.Op;
2
Article.findAll({
3
where: {
4
title: { [Op.like]: '%' + searchQuery + '%' },
5
description: { [Op.like]: '%' + searchQuery2 + '%' }
6
}
7
});
8
Sequelize < 4.12
JavaScript
1
7
1
Article.findAll({
2
where: {
3
title: { like: '%' + searchQuery + '%' },
4
description: { like: '%' + searchQuery2 + '%' }
5
}
6
});
7
The above will make sure title
includes searchQuery
and description
includes searchQuery2
. If you however would like to get results back when an Article includes one of the two, the following query should work:
Sequelize >= 4.12
JavaScript
1
10
10
1
const Op = Sequelize.Op;
2
Article.findAll({
3
where: {
4
[Op.or]: [
5
title: { [Op.like]: '%' + searchQuery + '%' },
6
description: { [Op.like]: '%' + searchQuery2 + '%' }
7
]
8
}
9
});
10
Sequelize < 4.12
JavaScript
1
9
1
Article.findAll({
2
where: {
3
$or: [
4
title: { like: '%' + searchQuery + '%' },
5
description: { like: '%' + searchQuery2 + '%' }
6
]
7
}
8
});
9