beingalex
beingalex

Reputation: 2476

Initialize a hydrator result set and aggregate in ZF2

I am joining two tables and have successfully managed to write a hydrator that outputs the following array:

    $sql = new Sql($this->dbAdapter);
    $select = $sql->select('misc_damage');
    $select->where(array('vehicle_id = ?' => $id))->order('date_added DESC');
    $select->join('user','user.user_id = misc_damage.added_user_id', 
            array(
                'user_display_name' => 'display_name', 
                'user_email' => 'email',
                'user_username' => 'username'
                ), 
    'left');

    $stmt = $sql->prepareStatementForSqlObject($select);
    $result = $stmt->execute();

    if ($result instanceof ResultInterface && $result->isQueryResult()) {

        $hydrator = new AggregateHydrator();
        $hydrator->add(new ClassMethods());
        $hydrator->add(new \Application\Hydrator\UserHydrator());

        $miscDamage = $hydrator->hydrate($result->current(), new \Application\Model\Miscdamage());
        var_dump($miscDamage);
        die();
    }

This produces 1 result:

/var/www/zf-skeleton/module/Application/src/Application/Mapper/ZendDbSqlMapper.php:95:
object(Application\Model\Miscdamage)[655]
  protected 'id' => string '97' (length=2)
  protected 'vehicle_id' => string '3' (length=1)
  protected 'added_user_id' => string '1' (length=1)
  protected 'description' => string 'sdfsdsdf' (length=8)
  protected 'date_added' => string '2016-04-15 08:19:17' (length=19)
  protected 'date_repaired' => null
  protected 'repaired_user_id' => null
  protected 'status' => string '0' (length=1)
  protected 'user' => 
    object(Application\Model\User)[664]
      protected 'user_id' => string '1' (length=1)
      protected 'username' => null
      protected 'email' => string '[email protected]' (length=13)
      protected 'display_name' => string 'Alex' (length=4)

There should be multiple results as each vehicle can have multiple damage entries. How would I go about using HydratingResultSet with my AggregateHydrator? I would also like to initialize the result: return $resultSet->initialize($result);

Any help is appreciated!

Upvotes: 1

Views: 419

Answers (1)

beingalex
beingalex

Reputation: 2476

I found out how to do this. Need to use HydratingResultSet and Reflection:

    use Zend\Stdlib\Hydrator\Reflection as ReflectionHydrator;    

    if ($result instanceof ResultInterface && $result->isQueryResult()) {

        $hydrator = new AggregateHydrator();
        $hydrator->add(new ClassMethods());
        $hydrator->add(new \Application\Hydrator\UserHydrator());

        $resultSet  = new HydratingResultSet(new ReflectionHydrator, new \Application\Model\Miscdamage());
        $resultSet->setHydrator($hydrator);

        return $resultSet->initialize($result);

    }

Upvotes: 2

Related Questions