Skip to content
Advertisement

How to use a function in select along with all the records in Sequalize?

Here is a Sequalize query below which retrieves a transformed value based on the table column value.

courses.findAll({
  attributes: [ [sequelize.fn('to_char', sequelize.col('session_date'), 'Day'), 'days']]
});

The above sequlaize query will return result equal to as followed SQL query.

select to_char(bs.session_date, 'Day') as days from courses bs;

Expected output:
I want the transformed value which is in attributes along with all records like below. I know we can mention all the column names in attributes array but it is a tedious job. Any shortcut similar to asterisk in SQL query.

select to_char(bs.session_date, 'Day') as days,* from courses bs;

I tried the below sequalize query but no luck.

courses.findAll({
  attributes: [ [sequelize.fn('to_char', sequelize.col('session_date'), 'Day'), 'days'],'*']
});

Advertisement

Answer

The attributes option can be passed an object as well as an array of fields for finer tuning in situations like this. It’s briefly addressed in the documentation.

courses.findAll({
    attributes: {
        include: [
            [ sequelize.fn('to_char', sequelize.col('session_date'), 'Day'), 'days' ]
        ]
    }
});

By using include we’re adding fields to the courses.* selection. Likewise we can also include an exclude parameter in the attributes object which will remove fields from the courses.* selection.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement