Amit
Amit

Reputation: 195

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.

Upvotes: 16

Views: 35192

Answers (4)

Joaquín Crippa
Joaquín Crippa

Reputation: 311

For those who still are looking for the solution to this problem. From https://github.com/sequelize/sequelize/pull/4029, if you add raw: true to the query, it removes the primary key.

Model.findOne({ 
  attributes: [
    [Sequelize.fn('SUM', Sequelize.col('field')), 'sum'],
  ],
  raw: true
})

Upvotes: 2

BartusZak
BartusZak

Reputation: 1253

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

Upvotes: 5

vapurrmaid
vapurrmaid

Reputation: 2307

I want to add that you can explicitly list the attributes you want and that they work on nested inner joins as follows:

const my_model = await MyModel.findById(id, {
  include: [
    {
      model: AnotherModel,
      attributes: [ 'displayName', 'email' ] // only these attributes returned
    },
    { model: YetAnotherModel,
      include: [{
        model: AnotherModel,
        attributes: [ 'id', 'displayName', 'email' ]
      }]
    }
  ]
})

Your returned Object should look like:

{
  // ...MyModel attributes
  ,
  AnotherModel: {
    displayName: '...',
    email: '...',
  },
  YetAnotherModel: {
    // ...YetAnotherModel's attributes
    ,
    AnotherModel: {
      id: '...',
      displayName: '...',
      email: '...',
    }
  }
}

Upvotes: 2

mcranston18
mcranston18

Reputation: 4790

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

MyModel.findAll({
  attributes: {exclude: ['some_field']}
});

Upvotes: 42

Related Questions