我使用Zend Framework 2和Doctrine 2.这是我的问题
以下命令返回对象数组
$results = $em->getRepository('MyProject\Domain\User')->find($id);
返回:
array (size=4)
0 =>
object(My\Entity\User)[3]
private 'id' => int 1
private 'firstName' => string 'joe' (length=3)
private 'lastName' => string 'smith' (length=5)
1 =>
object(My\Entity\User)[3]
private 'id' => int 1
private 'firstName' => string 'joe' (length=3)
private 'lastName' => string 'smith' (length=5)
3 =>
object(My\Entity\User)[3]
private 'id' => int 1
private 'firstName' => string 'joe' (length=3)
private 'lastName' => string 'smith' (length=5)
4 =>
object(My\Entity\User)[3]
private 'id' => int 1
private 'firstName' => string 'joe' (length=3)
private 'lastName' => string 'smith' (length=5)
我想将其转换为数组数组,如下所示:
array (size=4)
0 =>
array (size=3)
['id'] => int 1
['firstName'] => string 'joe' (length=3)
['lastName'] => string 'smith' (length=5)
1 =>
array (size=3)
['id'] => int 1
['firstName'] => string 'joe' (length=3)
['lastName'] => string 'smith' (length=5)
2 =>
array (size=3)
['id'] => int 1
['firstName'] => string 'joe' (length=3)
['lastName'] => string 'smith' (length=5)
3 =>
array (size=3)
['id'] => int 1
['firstName'] => string 'joe' (length=3)
['lastName'] => string 'smith' (length=5)
我尝试了以下内容:
$resultsArray = new \Doctrine\Common\Collections\ArrayCollection($results);
$resultsArray->toArray();
$resultsArray = new \Zend\Stdlib\ArrayObject($results);
$resultsArray->getArrayCopy();
两者都返回:
array (size=4)
0 =>
object(My\Entity\User)[3]
private 'id' => int 1
private 'firstName' => string 'joe' (length=3)
private 'lastName' => string 'smith' (length=5)
1 =>
object(My\Entity\User)[3]
private 'id' => int 1
private 'firstName' => string 'joe' (length=3)
private 'lastName' => string 'smith' (length=5)
3 =>
object(My\Entity\User)[3]
private 'id' => int 1
private 'firstName' => string 'joe' (length=3)
private 'lastName' => string 'smith' (length=5)
4 =>
object(My\Entity\User)[3]
private 'id' => int 1
private 'firstName' => string 'joe' (length=3)
private 'lastName' => string 'smith' (length=5)
我怎样才能做到这一点?建议的方法是什么?
答案 0 :(得分:1)
最简单的形式,以下是您想要的
$qb = $em->getRepository('My\Entity\User')->createQueryBuilder('User');
$result = $qb->getQuery()->getArrayResult();
通常,您使用自定义存储库并将DQL查询添加为文档中描述的方法
答案 1 :(得分:0)
传统上,我编写了一个自定义存储库类,并在其中调用getArrayResult()
$dql = 'MYDQLHERE';
$query = $this->getEntityManager()->createQuery($dql);
$query->execute();
$result = $query->getArrayResult();
我相信你的另一种选择是定制补水模式,虽然我没有经验。 http://docs.doctrine-project.org/en/latest/reference/dql-doctrine-query-language.html#custom-hydration-modes
答案 2 :(得分:0)
另一种编码方式,我使用它:
//at the top of custom repository class
use Doctrine\Orm\Query;
//in the method
$dql = "SELECT u FROM MyProject\Domain\User u WHERE u.id = $id"
$query = $entityManager->createQuery($dql);
$users = $query->getResult(Query::HYDRATE_ARRAY);
//knowing the code you provided, this should give you an array of four arrays