简体   繁体   中英

Doctrine queryBuilder: return object not array

I have this query created with doctrine querybuilder, the return i get is an array of arrays. I would like to get a return that is an array of objects, is this possible?

I know that normally Doctrine returns objects of an entity, bit since i have an inner join to get the name from another table it returns arrays.

Thanks in advance.

   $qb->select('u', 'h.name')
        ->from('AppBundle:UserHose', 'u')
        ->innerJoin('AppBundle:Hose', 'h', 'WITH', 'u.hoseId = h.id')
        ->where('u.userId = :userId')
        ->orderBy('u.id', 'DESC')
            ->setParameter('userId', $userId); 


    return $qb->getQuery()->getResult();

you can use this:

return $qb->getQuery()->getResult(Query::HYDRATE_ARRAY);

Or this:

return $qb->getQuery()->getArrayResult();

This isn't possible this way. In other words, you are doing it wrong.

You are telling Doctrine to return a collection of collections containing an entity and a string so this is what you get. Doctrine won't make an object out of that since it does not know how to hydrate such result.

[
  [entity, string],
  [entity, string],
  ....
]

If you wish to receive a collection of objects only, you would need to create a new entity that has both fields (related entity and a string property), then use a ResultSet mapping to hydrate that.

if you want array of objects you have to set relation betwen Entities, and create a query by the owning side of relation.

example:

Tourney entity , Invite entity

Invite
    /**
     * @ORM\ManyToOne(targetEntity="Tourney", inversedBy="invites")
     */
    protected $tourneys;

Tourney
    /**

     * @ORM\OneToMany(targetEntity="Invite", mappedBy="tourneys", cascade={"persist", "remove"})
     * @ORM\JoinColumn(nullable=true, onDelete="CASCADE")
     */
    protected $invites;

now you have to make query to the owning side of relation (Invite) and it will be holding all your join object data with Tourneys in field $invites

and it gives you array of objects. based on your query

remeber of setter $invites as setInvites(Tourney $invites) and by inverse side of relation setTourneys(Invite $tourneys)

Just add \\Doctrine\\ORM\\Query::HYDRATE_ARRAY on getResult() like this

$qb->select('u', 'h.name')
   ->from('AppBundle:UserHose', 'u')
   ->innerJoin('AppBundle:Hose', 'h', 'WITH', 'u.hoseId = h.id')
   ->where('u.userId = :userId')
   ->orderBy('u.id', 'DESC')
   ->setParameter('userId', $userId); 

return $qb->getQuery()->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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