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

标签 javascript sql node.js postgresql sequelize.js

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

让我用一个例子来说明我的意思: 我想创建一个网上商店,我有一个 Mobile 和一个 Feature 模型,它们之间存在多对多关系。该功能有一个多选过滤器(在我的网站上),我想列出那些具有选定功能的手机。 (例如:A B 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(但这只是一个假设,按您的方式行事;))

如果我理解你的问题是对的: 加入移动和功能表。然后在结果上使用 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"]

然后您在此处输入代码使用having使用之前创建的countedFeatures列:

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

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

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

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

关于javascript - 在 Sequelize 中使用具有多对多关系的 AND 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64817756/

相关文章:

node.js - 如何解决socket-io无限发送连接请求?

JavaScript - 无法正确访问对象内的属性

node.js - 带有嵌套插入的sequelize.js

javascript - 如何添加箭头图标以展开和折叠带有可展开行的 Angular Mat-Table 中的任何行?

javascript - 如何在 iPhone 触摸屏上实现 onmousedown 和 onmouseup

sql - 返回当前的 SSIS 错误计数

php - SQL 延迟加载 - 选择一个范围但丢弃之前选择的条目

javascript - react 堆 : Infinite scroll with multiple different GET requests

javascript - 在 ExtJS 中单击按钮时不会选中动态创建的复选框

c# - 如何加速此 C# 函数/SQL 插入?