sequelize: Can't exclude association's fields from select statement in sequelize
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;
About this issue
- Original URL
- State: closed
- Created 9 years ago
- Reactions: 3
- Comments: 18 (3 by maintainers)
just use joinTableAttributes attribute
@AntonAL Did you manage to make it work?
@mickhansen
through: { attributes: [] }
doesn’t remove the join table fields from the SELECT. Tested with v4.37.6.This issue should be re-opened, as the provided solution no longer works.
How do this by
Model.getAssociatedModels()
?@mickhansen, It does’t work for “sequelize”: “^4.37.4”. Is there some alternative?
My code is following:
yep! on polymorphic relationships, defining the empty
through: { attributes: [] }
property solves the problem inv4.38.0
. it’s not exactly intuitive… but it it works.e.g.
@danistefanovic it worked for me in v4.37.10
through: { attributes: [] }
removed the join table fields from the SELECTtry upgrading to the latest version
@toxxiczny You’re a life saver! This isn’t even included in the types of sequelize-typescript, but works with an
as any
.This is what I’m using for my use case where I want to exclude a field from the associated record.