简体   繁体   English

教义2实体饮水机

[英]Doctrine 2 entity hydrator

Is there way to hydrate entity data like as after doctrine query 有没有办法像教义查询之后那样合并实体数据

$entityData = $this->entityService->find($id)->getArrayResult();

and do it if you already have entity 如果你已经有实体就去做

$entity = $this->entityService->find($id)->getOneOrNullResult();
$entityData = $SomeDoctrineService->entityToArray($entity);

Solution

Firstly you can use \\DoctrineModule\\Stdlib\\Hydrator\\DoctrineObject 首先,您可以使用\\ DoctrineModule \\ Stdlib \\ Hydrator \\ DoctrineObject

$hydrator = DoctrineObject(
        $entityManager,
        get_class($entity)
    );

$entityData = $hydrator->extract($entity);

and secondly I've added custom hydrator trait EntityDataTrait 其次,我添加了自定义水化器特征EntityDataTrait

use Doctrine\ORM\Proxy\Proxy;
trait EntityDataTrait
{
    /**
     * @return array
     */
    public function toArray()
    {
        $data = get_object_vars($this);

        if ($this instanceof Proxy) {
            $originClassName = get_parent_class($this);

            foreach ($data as $key => $value) {
                if (!property_exists($originClassName, $key)) {
                    unset ($data[$key]);
                }
            }
        }

        foreach ($data as $key => $value) {
            if (method_exists($this, 'get' . ucfirst($key))) {
                $data[$key] = $this->{'get' . ucfirst($key)}();
            }
        }

        return $data;
    }
}

for example 例如

class MyEntity {
  use EntityDataTrait;

  /*properties and methods below*/
}

$entity = new MyEntity();
$entityData = $entity->toArray();

I'm afraid there is no built in doctrine functionality for this. 恐怕没有内置的学说功能。 You should create your own serializer or use one of existent ones: JMS Serializer, Symfony Serializer. 您应该创建自己的序列化程序或使用现有的序列化程序之一:JMS序列化程序,Symfony序列化程序。

You can create your own serializer as well. 您也可以创建自己的序列化器。 Sample code could be found here Doctrine2 export entity to array but it was mentioned that it is not the best approach. 示例代码可以在此处找到Doctrine2将实体导出到数组,但是有人提到这不是最好的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM