Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 314
Philippe Schwyter Avatar asked Apr 12 '16 16:04

Philippe Schwyter


1 Answers

I did some more digging and realized 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')
like image 54
Philippe Schwyter Avatar answered Oct 27 '22 13:10

Philippe Schwyter