Relationship count after create

I am working on an API with adonis.js and would like to return the count based on a relationship after creating a new record, example:

const data = request.only(['name'])
const category = await BlogCategory.create(data)

await category.loadCount('posts')  //It does not work

return category

For what purpose would I like to do this? since count will always be zero?

I want to return a default category structure for the front end, for example

in the array that holds the category listing, each category has the blog count, when it is a new category it must have the same structure no matter if it has 0

The only way to solve this would be to use withCount('posts') in a new database search?

I have not come across a loadCount so far. Why don’t you do a load and do a child count? Or you could always fall back on a count fetch as you mentioned.

I don’t know and can’t comment on why you are doing such a design - but I would create an object with zeros and return that if I simply want the structure and know for sure that there will be zero records.


the problem of creating an object with zero value

"__meta__": {
    "posts_count": 0

Would it be too verbose, if I would have to repeat the same thing on every controller I need counting after creation? this option is not feasible

Why don’t you do a load and do a child count?

I believe it is not good practice, after creating a record, to consult the same record again.

you need to take into consideration that I am dealing with an API, this solution I will apply to all controllers, so the solution needs to be clean, I believe that assembling an object manually or doing a second query is not the right way.

I believe you can simply do a count query as such.

const count = await category.posts().getCount()
return Object.assign(category.toJSON(), { count })

Code isn’t tested, but should work


The query works, but returns a different structure from the listing.

index() method return

"__meta__": {
    "posts_count": 0

your code

"count": 0

I need to always return to the front end the same structure.