Home > Software design >  How to use mySql function in Sequelize Typescript
How to use mySql function in Sequelize Typescript

Time:02-24

I want to use Year function on date column as I want to compare year

In raw format we can write query like this
Select * from Table where YEAR(date) = 2020

How can we convert this query in sequelize-typescript

class VenueSeason  {

...


@AllowNull(false)
@Column(DataTypes.STRING(255))
name?: string;

@AllowNull(false)
@Column(DataTypes.DATE)
startDate?: Date;

@AllowNull(false)
@Column(DataTypes.DATE)
endDate?: Date;

}

CodePudding user response:

To use mysql functions in Sequelize Typescript you can simply do this:

where: {           
          // anyOtherColumn: //value,
          [Op.and]: where(fn('YEAR', col('startDate')), _year),
        }

Do import the requirements for it from sequelize at top:

import { Op, fn, col, where } from "sequelize";

I got the hint from this question for Sequelize (Javacript) Sequelize WHERE sequelize.fn(...) AND something='something' ordering issue

  • Related