简体   繁体   English

Sequelize [Op.and] 不与 M:N 关联一起工作

[英]Sequelize [Op.and] not working with M:N association

I have two models我有两个模型

Units and Filters which are related with M:N association through unit_filter table通过 unit_filter 表与 M:N 关联相关的 Units 和 Filters

 this.belongsToMany(Unit, {
        through: "unit_filter",
        as: "units",
      });

  this.belongsToMany(Filter, {
        through: 'unit_filter',
        as: 'filters',
      });

The goal is to fetch units which have more than 1 filter associated with and condition.目标是获取具有超过 1 个与条件关联的过滤器的单元。

let result = await Unit.findAll({
          include: [
            {
              model: Filter,
              where: {
                id: {
                  [Op.and] : [2,252,4,80]
                }
              },
              as: 'filters',
            },
          ],
        });

The above is only working if there is only one id in the array which does not make any sense.只有在数组中只有一个没有任何意义的 id 时,上面的方法才有效。

Seqeulize documenation states序列化文档状态

  Post.findAll({
      where: {
       [Op.and]: [{ a: 5 }, { b: 6 }],            // (a = 5) AND (b = 6)
      }
    })

So the code I have should work theoritically.所以我的代码理论上应该可以工作。 I also tried with我也试过

where: {
   [Op.and] : [{id:2},{id:252},{id:4},{id:80}]
}

which results in getting all the items from the db.这导致从数据库中获取所有项目。 It does not even care about the where condition in this case.在这种情况下,它甚至不关心 where 条件。

Would be of great help if any one points me in right direction.如果有人指出我正确的方向,将会有很大的帮助。

You need to use Sequelize.literal with a subquery in where option in order to filter units that have more than 1 filter because simply indicating several ids of filters you will get units that have one of indicated filters (from 1 to N).您需要将Sequelize.literalwhere选项中的子查询一起使用,以便过滤具有 1 个以上过滤器的单元,因为只需指示多个过滤器 ID,您将获得具有指定过滤器之一(从 1 到 N)的单元。

let result = await Unit.findAll({
   where: Sequelize.where(
           Sequelize.literal('(SELECT COUNT(*) FROM unit_filter as uf WHERE uf.unit_id=unit.id AND uf.filter_id in ($filter_ids))'),
           Op.gt,
           '1'),
   bind: {
     filter_ids: [2,252,4,80]
   }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM