【问题标题】:Is it possible to get total counts in sub-sub queries in Objection js?是否可以在 Objection js 的子查询中获得总计数?
【发布时间】:2020-05-10 22:05:43
【问题描述】:

例如,我的用户有帖子(HasMany)和帖子,其中有属于用户和帖子的喜欢。因此,当尝试让所有用户发布与每个用户相关的帖子时,我会获取每个帖子中的总喜欢数。

const users = User.query().withGraphFetched('[posts.[likes, files]]')
      .select(['user_table.*', User.relatedQuery('posts').count().as('totalPosts')])

在上面的例子中,我得到了 totalPosts。没关系,但是如果我想在每个帖子中获得总赞怎么办?

最终期待这样的事情:

const users = User.query().withGraphFetched('[posts.[likes, files]]')
      .select(['user_table.*', User.relatedQuery('posts').innerRelated('likes').count().as('totalLikes')])

并且期望用户的输出数组如下:

[{
   id: 9323,
   firstName: 'John',
   lastName: 'Travolta',
   posts: [{
      id: 2,
      totalLikes: 99,
      files: [File],
   }],
   bio: 'Actor'
}]

【问题讨论】:

    标签: knex.js objection.js


    【解决方案1】:

    所以。找到了解决办法。如何做到这一点:

    const users = await User.query()
          .withGraphFetched('[web, posts.[likes, files, comments]]')
          .modifyGraph('posts', builder => {
            builder.select('post_table.*', Post.relatedQuery('likes').count().as('totalLikes'));
          });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-16
      • 1970-01-01
      • 2010-10-12
      • 1970-01-01
      • 2012-02-17
      • 1970-01-01
      相关资源
      最近更新 更多