Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to search integer using ilike in sequelize

Tags:

sequelize.js

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.

like image 721
leogoesger Avatar asked Oct 12 '25 18:10

leogoesger


1 Answers

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