2016-04-21 53 views
0

我在試圖瞭解如何最好地對使用Sequelize和Node.js的多個實體執行查詢。對複雜關係進行序列化和查詢

我已經定義了一個模型「用戶」,它與模型「位置」具有belongsToMany關係。然後我有一個「資產」模型,它與「位置」也有一個belongsToMany關係。當我有用戶的實例時,我想要獲取與用戶關聯的位置相關聯的所有資源。

我想這似乎並沒有工作,下面...

user.getLocations().then(function(userLocations) { return Asset.findAll({ where: { "Locations" : { $any : userLocations } }) }) 

任何人都可以提出任何建議?

回答

1

嘗試此查詢:

User.findById(user_id, { 
    include: [{ 
     model: Location, 
     required: true 
    }] 
}).then(user => Asset.findAll({ 
    where: { 
     user_id: user.id, 
     location_id: { 
      $in: user.locations.map(location => location.id) 
     } 
    } 
})).then(assets => { 
    // The rest of your logic here... 
}); 
+0

感謝。這使我走向了正確的方向。除此之外,我必須在「包含」中明確指定「as」,因爲在定義關係時指定了「as」。此外,由於資產和位置之間存在一對多關係,因此在查詢資產時必須包含位置。我將附上最後的查詢作爲單獨的答案。 – Michael

0

這是最後的結果......

User.findById(user_id, { 
    include: [{ 
     model: Location, 
     as: 'Locations', // Was needed since the original relation was defined with 'as' 
     required: true 
    }] 
}).then(user => Asset.findAll({ 
    include: [{ 
     model: Location, 
     as: 'Locations', 
     where: { 
      id: { 
       $in: user.Locations.map(location => location.id) 
      } 
     } 
    }] 
})).then(assets => { 
    // The rest of your logic here... 
});