【问题标题】:Sequelize - Where clause through multiple joined tableSequelize - 通过多个连接表的 Where 子句
【发布时间】:2016-06-09 05:22:31
【问题描述】:

我在节点中使用 sequelize orm 将对象映射到 mysql db。基本上我有两个表 productcategory。一个产品属于一个类别,但一个类别可以有多个产品。在类别表中,我有一列“parent_id”引用了它自己的 id。最多可以有三个层次结构。

主要目标是找到属于父类别**某物的任何类别的产品,例如 26。我可以在 sql 中推断查询,如下所示。

select * from product as p join category as c on p.category_id = c.id join  
category as c1 on c1.id = c.parent_id join category as c2 
on c2.id = c1.parent_id where c.id = 26 or c1.id = 26 or c2.id = 26

在 sequelize 中,我尝试通过包含如下引用来进行预加载

{
        // upto three levels of category
        model : category,
        as : 'c',
        attributes : [ 'id' ],
        include : {
            model : category,
            as : 'c1',
            attributes : [ 'id' ],
            include : [ {
                model : category,
                as : 'c2',
                attributes : [ 'id' ]
            } ]
        }
    }

这种连接完美无缺,但如何适应 where 子句

c.id = 26 或 c1.id = 26 或 c2.id = 26

提前致谢。任何帮助将不胜感激。

【问题讨论】:

    标签: mysql node.js orm sequelize.js


    【解决方案1】:

    尝试在查询的每个级别添加“where 对象”。第一个 where 对象适用于表 c。第二个 where 对象,嵌套在 include 对象中,适用于表 c1,以此类推。

    {
        // upto three levels of category
        model : category,
        as : 'c',
        attributes : [ 'id' ],
        where { id : 26 },
        include : {
            model : category,
            as : 'c1',
            attributes : [ 'id' ],
            where { id : 26 },
            include : [ {
                model : category,
                as : 'c2',
                attributes : [ 'id' ],
                where { id : 26 }
            } ]
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-07-26
      • 2017-07-16
      • 1970-01-01
      • 2015-04-27
      • 1970-01-01
      • 2023-03-28
      • 2017-06-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多