Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove associations from the output in Sequelize?

I have a classMethod defined for the Model User

// model user.js
classMethods: {
    associate: function(models) {
        User.belongsToMany(models.project, {through: 'user_project', foreignKey: 'user_id', otherKey: 'project_id'})
    }
}

From a route in Express i then query for the projects of this user and output it as JSON

user.getProjects({
    attributes: ['id', 'title'],
})
.then(function(projects) {
    res.json(projects)
})

This works fine, except for the fact the output also contains the user_project property which I would like to hide/omit/remove

[
  {
    "id": 8,
    "title": "Some project",
    "user_project": {
       "created_at": "2017-02-16T22:52:48.000Z",
       "updated_at": "2017-02-16T22:52:48.000Z",
       "project_id": 8,
       "user_id": 5
     }
  },
  //etc.

I have tried various exclude and include statements, but the output always contains it.

Is there a way to not have this show up in the output?

like image 465
Hyra Avatar asked Oct 26 '25 10:10

Hyra


2 Answers

I stumbled upon the solution.

To remove the attributes from the joined table you can use joinTableAttributes, like so:

user.getProjects({
    attributes: ['id', 'title'],
    joinTableAttributes: []
})
.then(function(projects) {
    res.json(projects)
})

By doing that, it will remove the (see OP) output of the user_project table, and the result is:

[
  {
    "id": 8,
    "title": "Test Project",
  },
  {
    "id": 4,
    "title": "Another one",
  }
]
like image 162
Hyra Avatar answered Oct 29 '25 02:10

Hyra


You should try the following

 user.getProjects({
    attributes: ['id', 'title'],
    through: {
        attributes: []
    }
})
.then(function(projects) {
    res.json(projects)
})
like image 28
Keval Gohil Avatar answered Oct 29 '25 02:10

Keval Gohil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!