从doctrine查询响应数组

时间:2017-03-05 16:37:05

标签: php orm doctrine symfony

我正在运行以下查询以从数据库中获取两个实体。

   return $this->createQueryBuilder('a')
        ->select('a','u')
        ->where('a.api_key = :api_key')
        ->leftJoin(User::class, 'u', \Doctrine\ORM\Query\Expr\Join::WITH, 'a.user_id = u.id')
        ->setParameter('api_key', $key)
        ->getQuery()
        ->getResult();

查询按预期返回两个实体。但是,响应采用索引数组的格式。

array(2) {
    [0]=> object(AppBundle\Entity\ApiKey)
    [1]=> object(AppBundle\Entity\User)
}

您是否知道在doctrine中是否有一种方法可以使用实体名称作为索引将响应作为关联数组返回?或者是否有一个可以从查询响应中选择一个实体的学说函数?

我只是问,因为我不喜欢这样做:

 $apiKey = null;
 $username = null;
 foreach ($result as $row) {
     if($row instanceof ApiKey::class){
         $apiKey = $row->getApikKey(); 
     }
     if($row instanceof User::class){
         $user = $row->getUsername();
     }
 }

并且希望能够做到这样的事情:

 $apiKey = $result [ApiKey::class]->getApiKey();
 $username = $result [User::class]->getUsername();

1 个答案:

答案 0 :(得分:2)

试试这段代码:

$entities = $this->createQueryBuilder('a')
        ->select('a','u')
        ->where('a.api_key = :api_key')
        ->leftJoin(User::class, 'u', \Doctrine\ORM\Query\Expr\Join::WITH, 'a.user_id = u.id')
        ->setParameter('api_key', $key)
        ->getQuery()
        ->getResult();

$returnArray = array();
foreach ($entities as $entity) {
    $returnArray[get_class($entity)] = $entity;
}

return $returnArray;

如果您想要做得更好,请尝试以下代码:

<?php
namespace My\Doctrine\Hydration;
use Doctrine\ORM\Internal\Hydration\ObjectHydrator;

class ClassArrayObjectHydrator extends ObjectHydrator
{
    protected function hydrateAllData()
    {
        $result = parent::hydrateAllData();

        return $this->toClassArray($result);
    }

    protected function toClassArray(array $result)
    {
        $returnArray = array();

        foreach ($result as $entity) {
            $returnArray[get_class($entity)] = $entity;
        }

        return $returnArray;
    }    
}

应用程序/配置/ config.yml

orm:
     entity_managers:
       default:
         mappings: ~
         hydrators:
             ClassArrayObject: \My\Doctrine\Hydration\ClassArrayObjectHydrator

您的查询:

return $this->createQueryBuilder('a')
            // ...
            ->getResult('ClassArrayObject');