Skip to content

Can't exclude association's fields from select statement in sequelize #3664

Closed

Description

@andrx

I have the following code (simplified):

var group = sequelize.define("group", {
    id: {type: DataTypes.INTEGER, autoIncrement: false, primaryKey: true},
    name: type: DataTypes.STRING,
    parentId: DataTypes.INTEGER
}, { classMethods: {
        associate: function (models) {
            group.belongsToMany(models.item, { as:'items', foreignKey: 'group_id', through: models.group_item_tie });
        }}
});

var group_item_tie = sequelize.define("group_item_tie", {}, {freezeTableName: true});

var item = sequelize.define("item", {
    spn: { type: DataTypes.INTEGER, autoIncrement: false, primaryKey: true },
}, { classMethods: {
        associate: function (models) {
            item.belongsToMany(models.group, { foreignKey: 'spn', through: models.group_item_tie });
        }}
});

When I try to return some records with relationships, let's say like this:

dbcontext.group.findAll({
    where: { id: 6 },
    include: [{
                model: dbcontext.item,
                as: 'items',
                attributes: ['spn']
            }]
    })

I also get in result the fields from a tie table group_item_tie:

[{
    "id": 6,
    "name": "abc",
    "parentId": 5,
    "createdAt": "2015-05-06T15:54:58.000Z",
    "updatedAt": "2015-05-06T15:54:58.000Z",
    "items": [
        {   "spn": 1,
            "group_item_tie": {
                "createdAt": "2015-05-06 15:54:58.000 +00:00",
                "updatedAt": "2015-05-06 15:54:58.000 +00:00",
                "group_id": 6,
                "spn": 1
            }
        },
        {   "spn": 2,
            "group_item_tie": {
                "createdAt": "2015-05-06 15:54:58.000 +00:00",
                "updatedAt": "2015-05-06 15:54:58.000 +00:00",
                "group_id": 6,
                "spn": 2
            }
        },

I see it in generated sql query. How to exclude those from select statement? I've tried a few other things but was not successful.

I hope there is something cleaner then just doing:

delete item.group_item_tie;

Activity

  1. mickhansen commented on May 7, 2015

    @mickhansen
    Contributor
    include: [{
      model: dbcontext.item,
      as: 'items',
      attributes: ['spn'],
      through: {
        attributes: []
      }        
    }]
  2. andrx commented on May 7, 2015

    @andrx
    Author

    Thank you! Couldn't find information about this in documentation though

  3. janmeier commented on May 7, 2015

    @janmeier
    Member

    @andrx its on the todo list :) #2975

  4. GayathriMohan commented on Oct 24, 2017

    @GayathriMohan

    Is there any way I can exclude all the attributes in the model 'item' and just include the attributes present in the through model? @mickhansen

  5. AntonAL commented on Apr 10, 2018

    @AntonAL

    @mickhansen, It does't work for "sequelize": "^4.37.4".
    Is there some alternative?

    My code is following:

    Country.prototype.getCompanies = function(options={}){
        const include = [{
          model: conn.models.city,
          required: true,
          duplicating: false,
          attributes: [],
          through: {
            attributes: []
          },
          include: [{
            model: conn.models.region,
            required: true,
            duplicating: false,
            attributes: [],
            include: [{
              model: conn.models.country,
              attributes: [],
              where: {
                id: this.get('id')
              }
            }]
          }]
        }];
    
        return conn.models.company.findAll({
          where: options.where,
          attributes: ['id', 'name'],
          limit: options.first,
          include: include,
          order: options.order ? [options.order.split(' ')] : undefined
        });
      };
  6. mickhansen commented on Apr 10, 2018

    @mickhansen
    Contributor

    @AntonAL Define "doesn't work", what happens, what do you expect to happen, etc.
    In any case i'm still using v3.

  7. AntonAL commented on Apr 10, 2018

    @AntonAL

    @mickhansen See series of my last comments here #1897

  8. danistefanovic commented on Apr 24, 2018

    @danistefanovic

    @AntonAL Did you manage to make it work?


    Define "doesn't work", what happens, what do you expect to happen, etc.

    @mickhansen through: { attributes: [] } doesn't remove the join table fields from the SELECT. Tested with v4.37.6.

  9. maxbogue commented on May 22, 2018

    @maxbogue

    This issue should be re-opened, as the provided solution no longer works.

  10. dpkshrma commented on Jun 16, 2018

    @dpkshrma

    @danistefanovic it worked for me in v4.37.10
    through: { attributes: [] } removed the join table fields from the SELECT

    try upgrading to the latest version

  11. broox commented on Aug 14, 2018

    @broox

    yep! on polymorphic relationships, defining the empty through: { attributes: [] } property solves the problem in v4.38.0. it's not exactly intuitive... but it it works.

    e.g.

      MyDude.findOne({
        where: conditions,
        include: [{
          model: MyOtherDude,
          as: 'sub_dudes',
          attributes: ['name', 'slug'],
          through: {
            attributes: []
          }
      }).then((dude) => {
          ...
      });
    
  12. ryanburnette commented on Nov 4, 2018

    @ryanburnette

    This is what I'm using for my use case where I want to exclude a field from the associated record.

    db.Bar.findOne({
      where: {
        attr: 'foo'
      },
      include: [
        {
          model: db.Foo,
          attributes: {
            exclude: ['xattr']
          }
        }
      ]
    })
  13. wl1711 commented on Nov 8, 2018

    @wl1711

    it doesn't work for me, I tried v 4.37.1, 4.38.0 and 4.41
    opened another issue #10141

  14. mookilyu commented on May 16, 2019

    @mookilyu

    How do this by Model.getAssociatedModels()?

  15. MatheusJacob commented on Jun 25, 2019

    @MatheusJacob

    I couldn't make it work on getAssociateMOdels too...

  16. jochri3 commented on Jun 29, 2019

    @jochri3

    Thank you @mickhansen

  17. added a commit that references this issue on Sep 2, 2019
  18. kuubson commented on Jan 12, 2020

    @kuubson

    just use joinTableAttributes attribute

    await user.getCars({
        joinTableAttributes: [] 
    })
    
  19. santiagoramirez commented on Jun 15, 2020

    @santiagoramirez

    @toxxiczny You're a life saver! This isn't even included in the types of sequelize-typescript, but works with an as any.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions