Is there any simpler option how to get count number from relatedQuery?
Currently I am doing this
const followersCount = await user
.$relatedQuery('followers')
.count('*')
.pluck('count')
.first();
I have tried next code but it is not working without '*'. With '*' it will returns array [{ count: '22' }].
const followersCount = await user
.$relatedQuery('followers')
.count();
Unfortunately there's no easier way to do that at the moment. count('whatEver') simply adds a SELECT COUNT(whatEver) as count to the query.
I saw one solution for this case in another library. They have function scalar() in query builder. It will take first item from array and first item in the object.
You are able to change next code:
const followersCount = await user
.$relatedQuery('followers')
.count('*')
.pluck('count')
.first();
with
const followersCount = await user
.$relatedQuery('followers')
.count('*')
.scalar();
I am not sure if you are interested. Maybe it can be nice addon to current API. Here is implementation from another library https://github.com/codemix/oriento/blob/d2143edb8dc4051ab9b049381656b4c1eced2d35/lib/db/query.js#L81
[{ count }] => count
@koskimas what do you think about scalar method?
@koskimas @seeden That scalar method seems to be very useful!
@andrepcg yes it is. The strange thing is that you need to write different code for static and instance method.
static example:
await User
.query()
.count('*')
.pluck('count')
.first()
instance example (without first):
const res = await this
.$query()
.where((builder) => {
builder
.where('value', '>', value)
.where({ type });
})
.count('*');
return res.count;
Most helpful comment
I saw one solution for this case in another library. They have function scalar() in query builder. It will take first item from array and first item in the object.
You are able to change next code:
with
I am not sure if you are interested. Maybe it can be nice addon to current API. Here is implementation from another library https://github.com/codemix/oriento/blob/d2143edb8dc4051ab9b049381656b4c1eced2d35/lib/db/query.js#L81