SEQUELIZE: How to use the EXTRACT MySQL function

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

I can write:

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

I'm struggling to figure out how to write a sequestration query that includes more sophisticated 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 was the closest I can get:

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

The result is the following SQL:

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

Unlike

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

I do not understand how I can build this query correctly.

+5
source share
1 answer

I did a few more digging and realized that the correct solution was to use sequelize.literal() to add arbitrary parts to my SQL query.

The solution here is to use

 sequelize.literal('extract(YEAR_MONTH FROM `User`.`created_on`) AS created_year_month') 
+1
source

Source: https://habr.com/ru/post/1246965/


All Articles