Returning a ZF2 HydratingResultSet when starting with raw SQL – Rob Allen's DevNotes


If you're using Zend Framework 2's Zend\Db and want to write raw SQL that returns a HydratingResultSet, then you can do this:

When you iterate over the HydratingResultSet, you get a populated instance of MyEntity. The $hydrator instance is the object that knows how to populate your entity object. In my case, I've used an ArraySerializable hydrator, but there's other options available, or you can write your own.

As an aside, if you don't want hydrated entities, then the $result that's returned from the statement's execute() call is an instance of ZendDbAdapterDriverResultInterface which means that you can iterate over it and get an array for each row in the result set.