So I want to get the count of comments in a post rather than all the comments themselves
I've got it to work with modifyEager like so but the as('count')
seems to be doing nothing in this case
.eager('comments').modifyEager("comments", builder => {
builder.count().as('count')
})
It's really tedious because commentsCount for each post has these values:
[]
[]
[]
[]
[ Post { 'count(*)': 1 } ]
[]
So I have gotten the count doing this but I'm surely doing something wrong
if(commentCount.length > 0)
return data[0]["count(*)"]
return 0
Any ideas?
EDIT: showing the working code for reference to help people
module.exports = async (organizationId, scope) => {
return await Post.query()
.where("organization_id", organizationId)
.orderBy("post_id", "desc")
.limit(scope.limit)
.offset(scope.offset)
.select(
'posts.*',
Post.relatedQuery('comments').count().as('commentsCount')
)
.eager('users')
}
Couldnt test it, but the example appears at docs this way:
const posts = await Post
.query()
.select(
'Post.*',
Post.relatedQuery('comments').count().as('numberOfComments')
);
console.log(posts[4].numberOfComments);