如何在Sequelize中对belongsToMany关联进行顶级查询?

时间:2018-03-30 11:35:24

标签: associations sequelize.js eager-loading

我需要获得属于帖子的所有标签。

首先,我通过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个帖子。但tagBtagC在嵌套的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:[]},            
      }]
    })

有没有办法在结果中保留tagBtagC

1 个答案:

答案 0 :(得分:0)

Post.findAll,其中“TagA”返回id post,然后每个循环&gt;获取完整信息包括内部标签!