我需要获得属于帖子的所有标签。
首先,我通过belongsToMany
关联管理发布和标记,就像表post_tag
一样。这些模型的构建如下:
Post.belongsToMany(Tag, {
as: 'tags',
through: {
model: PostTag,
unique: true,
},
foreignKey: 'post_id',
constraints: true
});
Tag.belongsToMany(Post, {
as:'posts',
through: {
model: PostTag,
unique: true,
},
foreignKey: 'tag_id',
constraints: true
});
然后,我写了这样一个好的工作陈述:
Post.findAll({
include: [{
model: Tag, as: 'tags',
attributes: ['id','name'],
through: {attributes:[]}
}]
})
//JSON result
[
{
"title": "Post title 1",
"tags": [
{"id":1, "name": "tagA"},
{"id":2, "name": "tagB"}
]
},
{
"title": "Post title 2",
"tags": [
{"id":1, "name": "tagA"},
{"id":3, "name": "tagC"}
]
}
]
当我尝试按tagA
过滤帖子时,我上面仍然有2个帖子。但tagB
和tagC
在嵌套的tags
中丢失了:
Post.findAll({
include: [{
model: Tag, as: 'tags',
attributes: ['id','name'],
through: {attributes:[]},
where: {name:'tagA'} // <--- Add filter here
}]
})
//JSON result
[
{
"title": "Post title 1",
"tags": [
{"id":1, "name": "tagA"} // <-- tagB was gone
]
},
{
"title": "Post title 2",
"tags": [
{"id":1, "name": "tagA"} // <-- tagC was gone
]
}
]
我阅读Sequelize document,其中指导我们将where
移至顶级,但它仅适用于hasMany
关联。
Post.findAll({
where: {'$tags.name$':'tagA'} // <--- move query to top here follow the guide
include: [{
model: Tag, as: 'tags',
attributes: ['id','name'],
through: {attributes:[]},
}]
})
有没有办法在结果中保留tagB
和tagC
?
答案 0 :(得分:0)
Post.findAll,其中“TagA”返回id post,然后每个循环&gt;获取完整信息包括内部标签!