我正在加入两个表并成功设法编写一个输出以下数组的水合器:
$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 'alex@home.com' (length=13)
protected 'display_name' => string 'Alex' (length=4)
应该有多个结果,因为每辆车可能有多个损坏条目。如何将HydratingResultSet
与AggregateHydrator
一起使用?我还想初始化结果:return $resultSet->initialize($result);
感谢任何帮助!
答案 0 :(得分:2)
我发现了如何做到这一点。需要使用HydratingResultSet
和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);
}