【问题标题】:sequelize: how to do equivalent of findAndCountAll for associations续集:如何为关联做等效的 findAndCountAll
【发布时间】: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


    【解决方案1】:

    我之前遇到过这个问题,我决定用这种方式改变功能......

    const include = [
      {
        model: models.UserGroup,
        attributes: [],
        as: 'groups'
      }
    ];
    
    const [total, data] = await Promise.all([
        User.count({ distinct: true, include }),
        User.findAll({
           order: [sequelize.literal(`MAX("groups"."createdAt") desc`)],
           group: ['User.id'],
           include
        })
    ]);
    

    【讨论】:

      【解决方案2】:

      恐怕在急切加载关联时(或者至少当您还想为关联添加一些条件时)使用findAndCountAll 方法是不可能的。没有选项可以使用 user.getGroups() 获取有关关联项目总数的信息。

      虽然您可以使用 Sequelize 的简写方法来计算关联的实例,但在您的情况下,user.countGroups() 在返回 user.getGroups() 之前。如果您想获取具有某些条件的相关组,只需将它们作为getGroups() 方法参数传递(它与标准findAll 采用相同的选项参数)

      【讨论】:

        猜你喜欢
        • 2018-06-27
        • 1970-01-01
        • 1970-01-01
        • 2017-05-30
        • 2019-02-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多