2017-04-19 60 views
0

我的一個與sequ​​elize最大的痛苦做findAndCountAll當量爲從根本上「分頁和計數」的聯想。sequelize:如何爲社團

使用findAndCountAll對於一次性模型來說相當簡單,對於很多人來說有點痛苦,但完全不可能與多對多一起工作。

舉個例子,我有這麼多-to-many關聯建立,在那裏用戶可以屬於多個組:

const UserGroup = db.define('user_groups', { 
}) 
User.belongsToMany(Group, {through: UserGroup}) 
Group.belongsToMany(User, {through: UserGroup}) 

讓所有用戶從一組是直接的:

user.getGroups().then.... 

但移植這findAndCountAll只是似乎不相同的方式工作:

User.findAndCountAll({ 
     include: [{model: Group, 
          through: UserGroup, 
          where: { groupId : group.id, 
             userId : {$ne: user.id}} 
     }], 
     limit: limit, 
     offset: offset, ... 

這是行不通的,因爲它從where子句中Group模型相關聯的密鑰。

我也試過:

User.findAndCountAll({ 
     include: [{model: Group, 
          include: { 
           model: UserGroup, 
           where: { groupId : group.id, 
               userId : {$ne: user.id}}} 
     }], 
     limit: limit, 
     offset: offset, ... 

,但它也將失敗,與Error: user_groups is not associated to groups!,這是不是真的。

有沒有乾淨的方式來做到這一點,最好的輔助方法?

回答

0

恐怕沒有可能在急切加載關聯時(或者至少當你還想向關聯添加一些條件時)使用findAndCountAll方法。沒有任何選項來獲得有關使用關聯的項目總數的信息,在你的情況,user.getGroups()

雖然您可以使用Sequelize的速記方法來計算關聯的實例,在您的情況下,user.countGroups()在返回user.getGroups()之前。如果你想用一些條件來獲取相關的羣體,只是將它們作爲getGroups()方法參數(它需要相同的選項參數作爲標準findAll