Sequelize: load only certain field attributes when eager loading belongsToMany?

Created on 3 Mar 2015  路  3Comments  路  Source: sequelize/sequelize

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,

  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.

Most helpful comment

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

All 3 comments

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

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

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mujz picture mujz  路  3Comments

evantahler picture evantahler  路  3Comments

dylanpyle picture dylanpyle  路  3Comments

jpodwys picture jpodwys  路  3Comments

kasparsklavins picture kasparsklavins  路  3Comments