Sequelize - 包括所有子项(如果有匹配项)

3 mysql sql sequelize.js

我有两个实体,Post 和 Tag,我试图查询所有具有传递到 where 子句的任何一个标签的帖子。此外,我想包含最终帖子集的所有标签。

关联定义如下

Post.belongsToMany(
      models.tag,
      {
        through: 'post_tag'
      }
    );
Run Code Online (Sandbox Code Playgroud)

我的查询是这样的

models.post.findAll({
    limit: 20,
    offset: 0,
    attributes: [
        'id',
        'name'
    ],
    include: [{
        model: models.tag,
        attributes: ['name'],
        where: {
            name: {
                [Op.in]: ['tagNameHere']
            }
        }
    }],
    where: [{
      active: {
        [Op.not]: 'False'
      }
    }],
    order: [ ['name', 'ASC'] ]
})
Run Code Online (Sandbox Code Playgroud)

它确实有效,但包含的标签数组只是 Op.in 中指定的标签数组。我希望包含所有标签

有更好的办法吗?

小智 6

一种方法是进行两次传递:1)查找具有特定标签的帖子,2)查找这些帖子的所有标签。您需要第三个关联才能实现这一点:

models.post.belongsToMany(models.tag, {through: models.postTag, foreignKey: 'post_id'} );
models.tag.belongsToMany (models.post,{through: models.postTag, foreignKey: 'tag_id' });

models.post.hasOne(Post, {
   foreignKey: {name: 'id'},
   as: 'selfJoin'
});
Run Code Online (Sandbox Code Playgroud)

现在,识别具有特定标签(或多个标签)的帖子

models.post.addScope('hasParticularTag',
{
   attributes: ['id'],
   include: [
     {
       model: models.tag, 
       through: models.postTag,
       attributes: [],
       where: {name: 'TAG-YOU-WANT'}   // your parameter here...
     }]    
 });
Run Code Online (Sandbox Code Playgroud)

最后,列出选定的帖子及其所有任务......

models.post.findAll({    
   attributes: ['id','name'],
   include: [
      { // ALL tags
        model: models.tag, 
        through: models.postTag,
        attributes: ['name']
      },
      { // SELECTED posts
        model: models.post.scope('hasParticularTag'),
        required: true,
        as: 'selfJoin',   // prevents error "post isn't related to post"
        attributes: []
      }]
 })
Run Code Online (Sandbox Code Playgroud)

哈....