Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize cast column to integer in where clause

Trying to cast a column inside a where clause to search for a query against. Have a difficult time finding reliable documentation on how to do this. Any ideas?

return await User.findAndCountAll({
      where: {
        [Op.or]: {
          'email': { [Op.iLike]: `%${query}%` },
          '$id::text$': { [Op.iLike]: `%${query}%` } // id is int but needs to be string for searching
        }
      },
      limit,
      offset: page * limit,
      order: [[sortBy, sortOrder.toUpperCase()]],
      raw: true,
      logging: console.log
    });
like image 529
Ryan Salmons Avatar asked Nov 09 '17 21:11

Ryan Salmons


3 Answers

I think this is what you searching for:

where: {
          [Op.or]: [
            {email: {[Op.iLike]: `%${query}%`}},
            sequelize.where(
              sequelize.cast(sequelize.col('User.id'), 'varchar'),
              {[Op.iLike]: `%${query}%`}
            ),
          ],
        },
like image 182
leogoesger Avatar answered Oct 19 '22 01:10

leogoesger


As @leogoesger's answer didn't work for JSONB fields in Postgres, I tried this:

    where: {
        ["data.createdAt::timestamp"]: {
            [Op.lt]: "now() - interval '3 days'"
        }
    }

Lo and behold, it produced:

WHERE CAST(("User"."data"#>>'{createdAt}') AS TIMESTAMP) < now() - interval '3 days'

Using Sequelize 5.1.0.

like image 35
Slav Avatar answered Oct 18 '22 23:10

Slav


This worked for me:

Notification.findOne({ where: {
    [Op.and]: [
        sequelize.literal("cast(notify_data as CHAR) = "+game_id),
        {user: players[i].user, notify_type: type.id}
    ]
}});

Basically, sequelize.literal returns a string rather than a key-value pair, so I did a work around using Op.and which can take both strings and objects in its array

like image 2
RAHUL BHOLA Avatar answered Oct 19 '22 01:10

RAHUL BHOLA