首页 > 解决方案 > Sequelize 生成复杂查询(SELECT WHERE IN)

问题描述

我需要得到一个像这样的复杂查询。检查用户对 table1 数据的访问。使用 ORM Sequelize js。

SELECT *
FROM table1
WHERE id = 23
  AND "table2_id" IN
      (SELECT id
       FROM "table2"
       WHERE "table3_id" IN
             (SELECT id
              FROM "table3"
              WHERE "table_4" IN
                    (SELECT id
                     FROM table4
                     WHERE "table5_id" IN
                           (SELECT "id"
                            FROM "table5"
                            WHERE "userId" = 1))))

我尝试使用包含参数

const table1_item = await Table1.findOne({
        where: {id: id, '$table2.table3.table4.table5.user.id$': user.id},
        include: [
            {
                model: Table2,
                attributes: [],
                include: [{
                    model: Table3,
                    attributes: [],
                    include: [{
                        model: Table4,
                        attributes: [],
                        include: [{
                            model: Table5,
                            attributes: [],
                            include: [{
                                model: User,
                                attributes: [],
                            }]
                        }]
                    }]
                }]
            }
        ]
    });

但它使用 JOIN 生成查询。并且数据库正在慢慢返回许多数据行。

标签: javascriptsequelize.js

解决方案


The only option here is Sequelize.literal in where. See my answer about similar question


推荐阅读