Skip to content

load only certain field attributes when eager loading belongsToMany? #3258

Closed

Description

@maplesap

When I eager load belongsToMany, sequelize will return the join table along with the attributes. I would like just the attributes I specify. How can this be achieved? For example,

user
  belongsToMany(models.group, {through: "rosters", as: "clubs"});

group
  belongsToMany(models.user, {through: "rosters": as: "members"});

query:

models.user.find({
  where: { id: 1 }, 
  include: [
    { model: models.group, as: "clubs", attributes: ["name"] }
  ]
});

Which returns:

[  { dataValues: { name: 'test', rosters: [Object] }, .... ] 

where rosters will contain fields in the join table (userId, groupId, etc...).

I would just like to list a user's group names without having to return the join table too. I'm not sure if this matters, but I'm not defining an actual model for the join table. I just called it rosters for the table name.

Activity

  1. mickhansen commented on Mar 3, 2015

    @mickhansen
    Contributor

    You should be able to do include: [{model: .. through: {attributes: []}}]

  2. psabharwal123 commented on Oct 8, 2017

    @psabharwal123

    @mickhansen how would i do this for a 'belongsTo' association?

  3. bidiu commented on Oct 14, 2017

    @bidiu

    Same question here: what if the relation is 1 to m?

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