Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude primary key attributes from a sequelize query

I have a sequelize query from multiple tables inner joined together. I need to group them by on a nested include model but the sequelize query throws the primary key every time, even if I mention the attributes as: attributes:[].

However attributes:[] is working for nested include models.

like image 368
Amit Avatar asked Mar 04 '18 12:03

Amit


People also ask

What is findByPk in Sequelize?

findByPk ​ The findByPk method obtains only a single entry from the table, using the provided primary key. const project = await Project. findByPk(123); if (project === null) {

How does include work in Sequelize?

To wrap up, include takes an array of objects. These objects are queries of their own, essentially just Sequelize queries within our main query. Inside each include query we specify the associated model , narrow our results with where , and alias our returned rows with as .

How do I group in Sequelize?

In Sequelize, you can add the group option in your query method findAll() to add the GROUP BY clause to the generated SQL query. Now you want to select all firstName values and group any duplicate values of the column. Here's the code for calling the findAll() method on the model: const users = await User.


2 Answers

You can exclude any attributes by passing an exclude array into the attributes option:

MyModel.findAll({
  attributes: {exclude: ['some_field']}
});
like image 169
mcranston18 Avatar answered Sep 21 '22 17:09

mcranston18


For included models use attributes: ['prop_name']

Remember include/exclude will not affect nested tables use through: { attributes:[]}

Model.addScope('scope_name', {
      attributes: ['id', 'name'],
      include: [
        {
          model: models.role,
          as: 'roles',
          attributes: ['name'],
          through: {
            attributes: []
          }
        }
      ]

More details can be found here: https://github.com/sequelize/sequelize/issues/4074#issuecomment-153054311

like image 20
BartusZak Avatar answered Sep 20 '22 17:09

BartusZak