Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize How compare year of a date in query

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!

like image 707
Alvaro Joao Avatar asked Aug 09 '16 21:08

Alvaro Joao


2 Answers

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

like image 116
Jan Aagaard Meier Avatar answered Nov 19 '22 09:11

Jan Aagaard Meier


you have to add the date_part function to your query:

sequelize.where(sequelize.fn("date_part",'year',sequelize.col('dateField')), 2020)
like image 4
Naju Mat Isa Avatar answered Nov 19 '22 11:11

Naju Mat Isa