'SEQUELIZE: How to use EXTRACT MySQL function

Let's say I'm trying to extract YEAR_MONTH from the records in the user table

I can write:

SELECT EXTRACT(YEAR_MONTH FROM u.created_on)
FROM user u;

I am struggling to understand how to write a sequelize query that involves more complex MySQL methods.

I know I can use something like:

sequelize.fn('avg', sequelize.col('User.age')), 'avg_age']

for simple MySQL methods that take only one parameter.

This has been the closest I can get:

[sequelize.fn('extract', ['YEAR', 'FROM'],   
 sequelize.col('User.created_on')), 'created_year_month']

Which results in the following SQL:

extract('YEAR_MONTH', 'FROM', `User`.`created_on`) AS `created_year_month`

as opposed to

SELECT EXTRACT(YEAR_MONTH FROM u.created_on)
FROM user u;

I am at a loss as to how I can properly build this query.



Solution 1:[1]

const tasks = await Task.findAll({
  attributes: ['id',

    [ sequelize.literal('extract(year from "Task"."created_at"::timestamp)'), 'year']

]})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 iminiki