I have this setup, a many-to-many relationship between Users and Topics:
User.belongsToMany(Topic, {through: "UserTopics", timestamps: false});
Topic.belongsToMany(User, {through: "UserTopics", timestamps: false});
I try to get all the users and their topics, this query does it pretty well:
User.findAll({
attributes: { exclude: ["password"] },
include: [
{ model: Topic, attributes: ['id', 'name',] }
]
})
This is what it outputs:
[
{
"id": 1,
"firstName": "John",
"lastName": "Doe",
"CNP": "123",
"email": "john@gmail.com",
"validated": false,
"createdAt": "2021-02-15T21:46:52.000Z",
"updatedAt": "2021-02-15T21:46:52.000Z",
"topics": [
{
"id": 1,
"name": "crypto",
"UserTopics": {
"userId": 1,
"topicId": 1
}
},
...
},
...
]
But the problem that I have and I just can't figure why it happens is that UserTopics attribute that shows up for every topic a user has.
How do I get rid of it?
Read this https://sequelize.org/master/manual/advanced-many-to-many.html
If you want to exclude assosiation fields from result:
User.findAll({
attributes: { exclude: ["password"] },
include: [
{ model: Topic, attributes: ['id', 'name',] }
],
through: {
attributes: []
}
})
Thanks fatur for pointing out the page. The actual way to do this is a little bit different than what he wrote. The "through" attribute must be inside the array object, like this:
User.findAll({
attributes: { exclude: ["password"] },
include: [
{
model: Topic,
attributes: ["id", "name"],
through: {
attributes: []
}
}
]
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.