2016-02-26 51 views
2

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

主要目标是找到任何属于父类的任何类别的产品**某事,例如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

在此先感谢。任何帮助将非常感激。

回答

0

尝试在查询的每个级别添加“where对象”。第一个对象适用于表c的地方。第二个嵌套在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 } 
     } ] 
    } 
}