4

使用风帆 0.10.5/水线 0.10.15:

我找不到一个简单问题的答案:如何在不使用 populate() (将加载所有数据)的情况下计算关联的元素。

让我们与 via 建立一个简单的 many2many 关系:

User:
    attributes: {
        following: {
            collection: 'user',
            via: 'follower',
            dominant: true
        },

        follower: {
            collection: 'user',
            via: 'following'
        }

现在我需要集合的大小。目前我尝试

User.findById(1).populateAll().exec(function(err, user) {
   // count of followings -> user.following.length;
   // count of followers-> user.follower.length;
}

这导致加载集合。

  • 我在收集级别缺少计数功能,以避免填充/加载数据。
  • 是否有可能访问(自动生成的)连接表以直接在连接上运行计数查询?

就像是:

User.findById(1).count({'followings'}).exec(function(err, followings) {
...}

或者

UserFollowingFollow_FollowFollowing.countByUserFollowingFollowId(1).
    exec(function(err, followings) {
...}
4

1 回答 1

3

Waterline 确实提供了count查询方法,可以像这样使用它来解决您的问题:

User.count().where({follower: followerId})
.exec(function(err, numberOfFollowings) {
  //numberOfFollowings will be the integer that you need
})

followerId是您User.findOne()在示例中传递给的 id。

您还可以阅读有关此的Waterline 文档

于 2015-01-27T21:34:05.927 回答