Fetch elements filtering by association but include all associations for matched elements
See original GitHub issuemodels associations:
Picture.belongsToMany(Tag, { through: 'fee_picture_tag' });
Tag.belongsToMany(Picture, { through: 'fee_picture_tag' });
query:
const pictures = Picture.findAll({
distinct: true,
include: [
{
model: Tag,
attributes: ['id', 'name'],
},
],
});
result:
[
{
"id": 1,
"tags": [
{
"id": 1,
"name": "烹饪",
},
{
"id": 6,
"name": "书籍",
}
]
},
{
"id": 2,
"tags": [
{
"id": 3,
"name": "烘焙",
},
{
"id": 6,
"name": "书籍",
}
]
},
{
"id": 3,
"tags": [
{
"id": 2,
"name": "花艺",
},
{
"id": 6,
"name": "书籍",
}
]
}
]
I need to filter out the pictures with the tag by id = 3, the query is
const pictures = Picture.findAll({
include: [
{
model: Tag,
attributes: ['id', 'name'],
through: {
where: {
tagId: 3,
},
},
},
],
});
actual
[
{
"id": 1,
"tags": []
},
{
"id": 2,
"tags": [
{
"id": 3,
"name": "烘焙",
}
]
},
{
"id": 3,
"tags": []
}
]
expect
[
{
"id": 2,
"tags": [
{
"id": 3,
"name": "烘焙",
},
{
"id": 6,
"name": "书籍",
}
]
},
]
How to implement this query? thank you!
Issue Analytics
- State:
- Created 4 years ago
- Comments:7 (3 by maintainers)
Top Results From Across the Web
4 ways to filter has_many associations
This technique is a good choice when you need to filter your records by one or more attributes.
Read more >Is it possible to filter a query by the attributes in the association ...
I am trying to filter my query by the attributes of the joining table. I have 2 tables Cities and Categories which I...
Read more >Eager Loading - Sequelize
As briefly mentioned in the associations guide, eager Loading is the act of querying data of several models at once (one 'main' model...
Read more >Four Sequelize Associations You Should Know
There are 4 types of joins,. INNER JOIN: Returns records that have matching values in both tables. LEFT OUTER JOIN: Returns all records...
Read more >Model usage - Manual | Sequelize
find - Search for one specific element in the database ... total number records matching the where clause and other filters due to...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
I see, thank you. @papb
@noyobo Currently there is no way to do it with only one query. Once #10943 is solved, then it will be possible!