2016-02-26 98 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 } 
     } ] 
    } 
}