1
有沒有辦法來滋潤實體數據樣的學說查詢學說2實體水化
$entityData = $this->entityService->find($id)->getArrayResult();
後做,如果你已經有了實體
$entity = $this->entityService->find($id)->getOneOrNullResult();
$entityData = $SomeDoctrineService->entityToArray($entity);
解決方案
首先你可以使用\ DoctrineModule \ Stdlib \ Hydrator \ DoctrineObject
$hydrator = DoctrineObject(
$entityManager,
get_class($entity)
);
$entityData = $hydrator->extract($entity);
,其次我已經添加了自定義的水化特性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;
}
}
例如
class MyEntity {
use EntityDataTrait;
/*properties and methods below*/
}
$entity = new MyEntity();
$entityData = $entity->toArray();
請張貼您的解答作爲答案,而不是您的問題的一部分。 – 2015-10-09 09:41:57