2016-04-18 60 views
1

我将两个表,并已成功地管理写输出下面阵列的水化器:初始化水化结果集和骨料在ZF2

$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(); 
    } 

这产生1个结果:

/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) 

应该有多个结果,因为每辆车可以有多个伤害条目。我将如何使用HydratingResultSet与我的AggregateHydrator?我还想初始化结果:return $resultSet->initialize($result);

任何帮助表示赞赏!

回答

2

我发现如何做到这一点。需要使用HydratingResultSetReflection

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); 

    } 
+0

我不是100%确定添加'Reflection' hydator帮助。 '$ resultSet = new HydratingResultSet(new ReflectionHydrator ...'只为HydratingResultSet()设置hydrator和hydration对象,但它并没有开始水合作用,在下一行你基本上设置了你的'AggregateHydrator()'而不是'Reflection()'。so'Reflection()'hydrator不见了,并且不参与'$ resultSet-> initialize($ result)'。也许你做了一些其他的帮助? –