2

For example I have User which has Posts ( HasMany) and Posts which has Likes which belongs to User and Post. So, I tying to get total count of likes in each post when try to get all users with posts related to each user.

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

in above example I got totalPosts. It's ok, but what if I want to get in each post total Likes?

Eventually expecting something like this:

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

And expect output array with users like below:

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

1 Answers1

5

So. Found out a solution. The way how to do that:

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