$shops = $this->em->getRepository('models\Shop')->findAll();
为我的数组提供实体,但我需要将实体作为数组。
如何将实体转换为数组?
答案 0 :(得分:16)
Doctrine允许您在执行查询时指定水合模式,这样您就可以更改返回结果的数据类型。在这种情况下,您需要Query :: HYDRATE_ARRAY。它不允许您在存储库中找到的默认findAll()方法上指定它。您需要为它编写自己的DQL。
如果你需要一组entites作为数组:
$query = $em->createQuery('SELECT u FROM User u');
$entites = $query->execute(array(), Query::HYDRATE_ARRAY);
// If you don't have parameters in the query, you can use the getResult() shortcut
$query = $em->createQuery('SELECT u FROM User u');
$entities = $query->getResult(Query::HYDRATE_ARRAY);
如果您需要单个实体作为数组,例如。对于特定ID:
$query = $em->createQuery('SELECT u FROM User u WHERE u.id = ?1');
$query->setParameter(1, $id);
$entity = $query->getSingleResult(Query::HYDRATE_ARRAY);
这些方法在Query和AbstractQuery上定义。
答案 1 :(得分:12)
我有同样的问题。return get_object_vars($this)
不是一个好的解决方案,因为它也会转换内部的教义对象/属性。经过一些研究,我发现这个类:EntitySerializer从中创建干净的数组或JSON您的实体并删除不必要的项目。文档位于here。例如,我使用以下代码:
$patientProfile = $this->em->getRepository('Entities\Patientprofile')->findOneByuserid('2222222');
$entitySerializer=new Bgy\Doctrine\EntitySerializer($this->em);
$patientProfile=$entitySerializer->toArray($patientProfile);