【发布时间】:2017-04-19 10:55:01
【问题描述】:
我对 sequelize 最大的痛苦之一是基本上“分页和计数”以获取关联。
使用findAndCountAll 对于一次性模型来说相当简单,对于has-many 来说有点痛苦,但对于many-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!,这不是真的。
有没有一种干净的方法可以做到这一点,最好是使用辅助方法?
【问题讨论】:
标签: orm sequelize.js