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

Viewed 139

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'],'*']
});

2 Answers

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.

There is one shortcut to achieve the asterisk kind of selection in Sequalize. Which can be done as follows...

// To get all the column names in an array
let attributes = Object.keys(yourModel.rawAttributes);
courses.findAll({
  attributes: [...attributes ,
[sequelize.fn('to_char', sequelize.col('session_date'), 'Day'), 'days']]
});

This is a work around there may be a different option.

Related