javascriptmysqlnode.jstypescriptsequelize-typescript

How to use a MySQL function in Sequelize TypeScript


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

In raw format, we can write a 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;
}

Solution

  • 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 the top:

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

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