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.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With