Developing software in the Real World

Returning a ZF2 HydratingResultSet when starting with raw SQL

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.

7 thoughts on “Returning a ZF2 HydratingResultSet when starting with raw SQL

  1. Thanks, 'tricks' like that might be obvious to some, but it's that sort of examples that I'd like to see more in ZF2 docs.

    BTW. this blog really helps me with my project. I wish there was more active bloggers posting on ZF2.

  2. Thanks so much for this example. I'm new to Zend2 & really struggled to find a decent low-level mapper implementation for my model. This gives me the flexibility I need, especially with complex joins to create models.

  3. Would you use something like this to deal child entities from a JOIN query? Or is any kind of entity relationship an automatic "use an ORM" moment?

Thoughts? Leave a reply

Your email address will not be published. Required fields are marked *