在 Sequelize 中使用具有多对多关系的 AND 操作

Use AND operation with many to many relationship in Sequelize

我的问题简而言之:我想在连接 table 中使用 AND 操作。我认为这是现实生活中非常普遍的用例,但我还没有找到任何相关的文章、博客或问题。 (我觉得是我的错 :D)

让我用一个例子来说明我的意思: 我想创建一个网上商店,我有一个 Mobile 和一个 Feature 模型,它们之间存在多对多关系。该功能有一个多 select 过滤器(在我的网站上),我想列出那些具有 selected 功能的手机。 (例如:A and Band C ...) 我想我不能在一个查询中创建它,因为一列不能同时是 A 和 B,但我不确定。 示例:

    const mobiles = await models.mobile.findAll({
      where: '???',
      attributes: ['id', 'name'],
      include: [
        {
          model: models.feature,
          where: '???',
          attributes: ['id', 'name],
          through: {
            attributes: [],
          },
        },
      ],
    });

我对 Sequelize 和 SQL 解决方案也很感兴趣。

示例模型和预期结果:

const Mobile = sequelize.define('Mobile', {
  id: {
     autoIncrement: true,
     primaryKey: true,
     type: DataTypes.INTEGER,
  },
  name: {
    type: DataTypes.STRING
  }
}, {});

const Feature = sequelize.define('Feature', {
  id: {
     autoIncrement: true,
     primaryKey: true,
     type: DataTypes.INTEGER,
  },
  name: {
    type: DataTypes.STRING
  }
}, {});

Mobile.belongsToMany(Feature, { through: 'MobileFeature' });
Feature.belongsToMany(Mobile, { through: 'MobileFeature' });

// Example Data in DB (from mobile context)
const exampleData = [
{
  "id": 1,
  "name": "Mobile1",
  "features": [
    {
      "id": 1,
      "name": "A",
    },
    {
      "id": 2,
      "name": "B",
    },
    {
      "id": 3,
      "name": "C",
    },
  ],
},
{
  "id": 2,
  "name": "Mobile2",
  "features": [],
},
{
  "id": 3,
  "name": "Mobile3",
  "features": [
    {
      "id": 1,
      "name": "A",
    },
  ]
}
];

// Expected result
// Scenario: I want to list those mobiles which have A and C feature
const result = [
{
  "id": 1,
  "name": "Mobile1",
  "features": [
    {
      "id": 1,
      "name": "A",
    },
    {
      "id": 2,
      "name": "B",
    },
    {
      "id": 3,
      "name": "C",
    },
  ]
},
];

我认为这里的查询会比 where.

更复杂

你能提供SQL适合你问题的查询吗?我想您将需要使用 GROUP BY、COUNT 和 HAVING(但这只是一个假设,按照您的方式行事;))

如果我理解你的问题: 加入移动和功能表。然后在 result

上使用 where
WHERE: {
 name: { [Op.or]: [A,B,C] } // here we pass array of selected feature names to where. It returns mobiles only with this features. But we are looking for mobile with ALL features passed in array)
}

按 Mobile.name 分组,计算每部手机的功能,然后选择具有功能数量 = 用户选择的功能的手机(因此手机具有我们正在寻找的所有功能)。

当然最后是一个sequelize语句

更新:在对此答案的评论中回答您的问题:

首先你需要计算特征。所以我们将使用 COUNT 并将输出存储在 CountedFeatures 列中:

attributes: ['id', 'name', [sequelize.fn('COUNT', 'table.fieldToCount'), 'CountedFeatures']],

然后您需要使用 group 对其进行分组。使用示例:

group: ["table.name, table.id"]

然后您enter code here 使用 having 使用之前创建的 countedFeatures 列:

having: sequelize.where(sequelize.fn('COUNT', 'countedFeatures'), '=', searchedFeaturesArray.length)

所以代码结构看起来像这样:

(...).findAll({
  attributes: [...],
  include : [
    (...)
  ],
  group: [...],
  having: [...]
})

您还可以打开 SQL 语句记录到控制台以查看下面到底发生了什么。 为此,在 findAll 函数中添加 logging: console.log 作为属性。