【问题标题】:How to count association size with waterline/sails?如何计算与水线/帆的关联大小?
【发布时间】:2015-01-27 10:57:51
【问题描述】:

使用帆 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) {
...}

【问题讨论】:

标签: many-to-many sails.js one-to-many waterline sails-mongo


【解决方案1】:

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

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

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

您也可以阅读Waterline documentation 了解此内容。

【讨论】:

  • 你试过了吗?它对我不起作用! github.com/balderdashy/waterline/issues/…
  • @Vunb 抱歉回复晚了。我相信,当我发布此答案时,我对其进行了测试,并且它与问题中提到的风帆和水线版本一起使用。
猜你喜欢
  • 1970-01-01
  • 2014-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-08
  • 2014-08-01
  • 1970-01-01
相关资源
最近更新 更多