Sequelize cast column to integer in where clause

*爱你&永不变心* 提交于 2019-12-10 15:37:44

问题


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
    });

回答1:


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}%`}
            ),
          ],
        },



回答2:


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.



来源:https://stackoverflow.com/questions/47212187/sequelize-cast-column-to-integer-in-where-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!