Why can’t you load them as part of the initial request? As far as I know there’s no inbuilt support for what you’re trying to achieve, but even if there was, it would be messy. The code would have to bind a parameter for each record in the initial set. Something like this:
SELECT * FROM Comment
WHERE PostId IN (:p1, :p2, :p3, ...)
I suppose it could instead fetch every record from the Comment table and process them in PHP, but either way seems wrong. They should really be pulled as part of the initial query so they can be joined within the database engine.
Sometime the array of objects (the $posts in example) is a result from a different operation, process, etc, and that operation cannot be altered to include.
I work with objects with lots of relations, and subrelations (I used $posts only to present the problem).
If I work with "with" the resulting query(s) are quite large and slow. JOINS in MySql are slow even on highly optimized tables. If the relations are read in distinct, sequential mode, the queryes are much lighter and execute faster than one big query with lots of slow joins.
I’m guessing you’ll have to write your own implementation. I’m not sure how you can do it without either pulling huge amounts of data into PHP or binding lots of parameters though.