首页 > 解决方案 > 如何在sequelize中使用where条件实现子选择

问题描述

我有这些表:

有了这个结构

[
  "products" :
    {
        "id": 1,
        "orginalName": "146153-0100 ",
        "title": null,
        "stores": [
            {
                "id": 1,
                "stock": 100,
                "minOQ": 1,
                "maxOQ": 0              
            },
            {
                "id": 2,
                "stock": 100,
                "minOQ": 1,
                "maxOQ": 0,

            }
        ],
        "productproperties": [
            {
                "id": 1,
                "productId": 1,
                "propertyId": 8,
                "propertyOptionId": 5
            },
            {
                "id": 2,
                "productId": 1,
                "propertyId": 9,
                "propertyOptionId": 11
            },
            {
                "id": 3,
                "productId": 1,
                "propertyId": 10,
                "propertyOptionId": 9
            }
        ]
    }
]

我想按选定的选项过滤我的产品,假设选定的选项是 11 和 9

如何在 Sequelize 5.6 中使用 findAll 、 where 和 ... 实现以下 sql 查询:

select * from products as p 
inner join stores as sr on sr.productId = p.id 
where (select count(*) from productProperties where propertyOptionId in (11,9) and productId = p.id) >= 2

标签: mysqlnode.jssequelize.js

解决方案


我发现在 sequelize 中使用查询生成器真的很令人困惑,所以如果你对原始 sql 很好,你可以按如下方式运行它们

如果 Student 是你的模型,那么 const students = Student.query('Select * from students');


推荐阅读