Sequelize How compare year of a date in query

十年热恋 提交于 2020-06-24 12:29:48

问题


I'm trying to make this query:

SELECT * FROM TABLEA AS A WHERE YEAR(A.dateField)='2016'

How can I perfome this query above in sequelize style?

TABLEA.findAll({
      where:{}//????
     }

Thanks!


回答1:


TABLEA.findAll({
  where: sequelize.where(sequelize.fn('YEAR', sequelize.col('dateField')), 2016)
 });

You have to use .where here, because the lefthand side of the expression (the key) is an object, so it cannot be used in the regular POJO style as an object key.

If you want to combine it with other conditions you could do:

TABLEA.findAll({
  where: {
    $and: [
      sequelize.where(sequelize.fn('YEAR', sequelize.col('dateField')), 2016),
      { foo: 'bar' }
    ]
  }
 });

https://sequelize.org/v3/docs/querying/#operators




回答2:


you have to add the date_part function to your query:

sequelize.where(sequelize.fn("date_part",'year',sequelize.col('dateField')), 2020)



回答3:


TABLE.findAll({
  where: sequelize.where(sequelize.fn('YEAR', sequelize.col('dateField')), 2016)
 });

You have to use .where here, because the lefthand side of the expression (the key) is an object, so it cannot be used in the regular POJO style as an object key.

If you want to combine it with other conditions you could do:

var Sequelize require('sequelize')
var Op = Sequelize.Op
let andOp = Op.and

TABLE.findAll({
  where: {
     foo: 'bar',
     andOp:sequelize.where(sequelize.fn('YEAR', sequelize.col('dateField')), 2016)   
  }
 });

https://sequelize.org/v5/manual/querying.html#operators



来源:https://stackoverflow.com/questions/38861087/sequelize-how-compare-year-of-a-date-in-query

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