What is an efficient, OOP way to count child records of an object?
In my current project, a District may contain zero or more School records. The Districts object acts as a collection of District, and can perform a single query to get the data behind several District in one go, rather than each District (Active Record) querying for its own data. District->schools() provides access to child schools.
On the page in question, I want to list all the districts and a count of their child schools. This is getting very sluggish as the number of districts grows, as each district must again query the schools table. Additionally, the database driver we're using does not provide a row count for the record set, so that would be another query. Some things I've considered:
- An optional object available through a service locator which can provide counts.
- Storing the child count with the parent record.
So, my current method of counting child records is pretty heavy. What are some ways I could lighten this load?