Is your feature request related to a problem? Please describe.
When getting a count for a 1:m or m:n relation you first need to populate the relation. This triggers first a select * query, requesting all data from the database, creating entities and cluttering the entity map.
Describe the solution you'd like
There should be an async count() method, maybe loadCount() that can count the relation without loading all entities. This method should trigger a select count(*) query.
Additional context
Example: a Organization has many Teams. My API can return the Organization with a count of the number of teams, but without returning the teams itself.
I don't know if someone is currently working on it, but I would be interested in contributing.
I juste have a few questions :
I'd say we should cache the value, having refresh parameter on the method to allow ignoring the cache. If the collection is initialized, it still might not have all the items loaded as it might be loaded with some where condition, so if we want to use the items.length, we need to add property to know how the collection items were loaded - as if can use the number only if there was no condition provided by user (but it should ignore global filters i'd say).
Regarding adding elements to the collection, either increment the cached value, or wipe it. Same needs to happen with remove and set methods, and probably also in hydrate method.
I guess we should have the method on the ArrayCollection too, returning the items.length, so the interface is same.
Do we also take filter into account?
It should work just fine, as it is using em.count() under the hood, which already handles filters:
https://github.com/mikro-orm/mikro-orm/pull/955/files#diff-b920c824d3abca88e17b05d7b566fcb0f8adca970d873e5de7580e8696f2c500R62