Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize select only chosen attributes

I am using MySQL database, when I am doing:

models.modelA.findAll({
            attributes: [
               ['modelA.id','id']
            ],
            raw: true,
            include:
                [
                    {
                        model: models.modelB,
                        required: true
                    }
                ]

        }).then(function (tenants) {

        });

Nevertheless that I've selected only id, Sequelize is retrieving all attributes, from related table as well so I'm getting {id, ... All attributes here}.

How I can prevent this? Sometimes I want to select only 2/3 columns and Sequelize is always selecting all of them what is not efficient.

like image 308
Marcin Avatar asked Mar 01 '18 14:03

Marcin


People also ask

What does the where option do in Sequelize?

The where option is considered for finding the entry, and the defaults option is used to define what must be created in case nothing was found. If the defaults do not contain values for every column, Sequelize will take the values given to where (if present). Let's assume we have an empty database with a User model which has a username and a job.

How does Sequelize handle finder results?

By default, the results of all finder methods are instances of the model class (as opposed to being just plain JavaScript objects). This means that after the database returns the results, Sequelize automatically wraps everything in proper instance objects.

What is Sequelize in JavaScript?

Since the above was an OR involving the same field, Sequelize allows you to use a slightly different structure which is more readable and generates the same behavior: Sequelize provides several operators. Passing an array directly to the where option will implicitly use the IN operator:

Is it possible to remove selected attributes from a query?

Similarly, its also possible to remove a selected few attributes: SELECT id, foo, bar, quz ... Whether you are querying with findAll/find or doing bulk updates/destroys you can pass a where object to filter the query.


1 Answers

You can do something like the following

models.modelA.findAll({
        attributes: [
           'id'
        ],
        raw: true,
        include:
            [
                {
                    model: models.modelB,
                    attributes: ['fieldName1', 'fieldName2'], // Add column names here inside attributes array.
                    required: true
                }
            ]

    }).then(function (tenants) {

    });
like image 111
Bharathvaj Ganesan Avatar answered Nov 13 '22 20:11

Bharathvaj Ganesan