You basically have 3 options:
- fetch the whole collection and filter afterwards (terribly slow = smell)
- fetch only the entries you need by checking the actual relations (pretty slow)
- store the relation-count and fetch by checking for the count (still slow + complex = smell)
Option 1 obviously doesn't make sense at all. Using option 3 you can easily end up in a corrupted application-state (the count/state-flag not matching the real state/count).
Now what's the solution? You should cache the result of option 2.
Create a postPersist
/ postUpdate
/ postRemove
doctrine subscriber that triggers the renewal of the result-cache without letting the client wait.
Either perform the cache-warming inside a subscriber to the kernel.terminate
event (after the response has been sent) ... or inside a periodically executed cronjob ( i.e. at a time where there is less user-activity ).
This way you ensure the result is definitely matching a real database state, have the best performance (no database-query the client has to wait for) ... and there is no unnecessary code bloating your entity + adding complexity.