Symfony findAll()返回错误类型的结果集

时间:2017-07-31 06:04:52

标签: php symfony doctrine

我正在使用php symfony框架。我想从用户表中获取所有行。这就是我写作的原因

$repository = $this->getDoctrine()->getRepository(User::class);
$users = $repository->findAll();

但是它的数组返回一种奇怪的数组。

Array ( 
            [0] => AppBundle\Entity\User Object ( [id:AppBundle\Entity\User:private] => 1 [roll:AppBundle\Entity\User:private] => 1 [name:AppBundle\Entity\User:private] => kumar [password:AppBundle\Entity\User:private] => 123456 ) 
            [1] => AppBundle\Entity\User Object ( [id:AppBundle\Entity\User:private] => 2 [roll:AppBundle\Entity\User:private] => 2 [name:AppBundle\Entity\User:private] => arpan [password:AppBundle\Entity\User:private] => 1234 ) 
            [2] => AppBundle\Entity\User Object ( [id:AppBundle\Entity\User:private] => 3 [roll:AppBundle\Entity\User:private] => 3 [name:AppBundle\Entity\User:private] => Bumba [password:AppBundle\Entity\User:private] => abcd ) 
        )

现在,如果我尝试返回 新响应(json_encode($ users)) ,则会返回[{},{},{}]。帮助我。

1 个答案:

答案 0 :(得分:4)

它返回的是一系列对象。通常这是你想要的,因为它自动绑定/保湿你创建的所有实体,所以你现在可以调用$result->getFoo()

但是,由于您似乎想要一个json结果,您应该拨打->getArrayResult()而不是->findAll()

像这样:

$query = $this->getDoctrine()
        ->getRepository('User entity namespace') // probably AppBundle/Entity/User
        ->createQueryBuilder('u') 
        ->getQuery(); 
 $result = $query->getArrayResult();

高度建议您从上到下阅读文档大约10次,尤其是Symfony&学说部分https://symfony.com/doc/current/doctrine.html