Norbert
Norbert

Reputation: 2771

Get count from Objection.js query using withGraphJoined

I have a really simple query and I'm trying to get the count.

const query = Product.query()
  .withGraphJoined('collections')
  .whereIn('collections.id', [1,3]);

I tried resultSize(), which worked on other queries I made that didn't use withGraphJoined. The only thing that works is if I do count() on the query, which returns the following:

Product {
  'count(*)': 6,
  id: 1,
  name: 'product',
  slug: 'slug',
  price: 32,
}

Is there a cleaner way to do a total count on queries with withGraphJoined?

Upvotes: 1

Views: 5194

Answers (1)

user6269972
user6269972

Reputation: 319

You are trying to count the collections associated with the Product? You can just do:

const query = Product.query()
  .whereIn('id', [1,3])
  .select([
     Product.ref('*'),
     Product.relatedQuery('collections').count().as('collectionsCount')
  ])

Upvotes: 4

Related Questions