How to get a Collection in Doctrine2's query results

前端 未结 3 2006
误落风尘
误落风尘 2021-01-31 02:42

I am trying to execute a query using doctrine2 and need it to return a collection object.

Simplified snippet:

$players = $this->getEntityManager()
            


        
相关标签:
3条回答
  • 2021-01-31 03:22

    to return an object instead of array, you have to use "Partial Objects".

    here is tested code example https://stackoverflow.com/a/12044461/1178870

    0 讨论(0)
  • 2021-01-31 03:37

    Since you're selecting only 'p' objects (and no individual column or aggregate values) and you're using getResult() for the hydration mode, your query should be returning pure objects rather than an array.

    My best guess is that the problem has to do with the shorthand syntax you're using to build the query. The first thing I'd try is writing out the query "long form" like this:

    $em = $this->getEntityManager();
    $qb = $em->createQueryBuilder();
    
    $qb->select('p')
       ->from('...\Player', 'p');
    
    $query = $qb->getQuery();
    $players = $query->getResult();
    

    I would have guessed that your shorthand approach would be fine, but I've found Doctrine to be kind of finicky when it comes to method chaining.

    There are a couple other things to consider depending on how simplified your snippet is. But in my experience, the query written as shown will return Player objects.

    0 讨论(0)
  • 2021-01-31 03:46

    The getResult() always returns an array. If you want a collection, you must pass the array that is returned by getResult() to Doctrine's ArrayCollection

    e.g.

    use Doctrine\Common\Collections\ArrayCollection;
    
    $result = $this
        ->getEntityManager()
        ->createQueryBuilder()
        ->select('p')
        ->from('...\Player', 'p')
        ->getQuery()
        ->getResult()
    ;
    
    $players = new ArrayCollection($result);
    
    0 讨论(0)
提交回复
热议问题