问题
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