I want to search row id = 123, if i have input field with 12 as input. Right now I have
where: {
id: {
[Op.iLike]: `%${req.body.gaugeId}%`,
},
},
This works if I am searching text fields, but it does not work for searching integer fields. I understand this is related to casting, but I could have find a way to implement this.
Figured out the solution. I run into couple issues.
First I didn't understand how casting work. I need to cast on a sequelize column, and to access the column, you need to use Model.column_name
.
Second Problem I run into was because I was casting to string
, instead of varchar
.
search(req, res) {
return Gauge.findAll({
where: sequelize.where(
sequelize.cast(sequelize.col('Gauge.id'), 'varchar'),
{[Op.iLike]: `%${req.body.gaugeId}%`}
),
}).then(gauges => {
res.status(200).send(gauges);
});
},
And if you want to use sequelize.or
, you can do the following:
return Gauge.findAll({
attributes: ['id', 'stationName'],
where: {
[Op.or]: [
{stationName: {[Op.iLike]: `%${req.body.keyWord}%`}},
sequelize.where(
sequelize.cast(sequelize.col('Gauge.id'), 'varchar'),
{[Op.iLike]: `%${req.body.keyWord}%`}
),
],
},
})
Here you can find more. https://github.com/sequelize/sequelize/issues/3565
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