Doctrine queryBuilder:return 对象不是数组

Doctrine queryBuilder: return object not array

我用 doctrine querybuilder 创建了这个查询,我得到的 return 是一个数组数组。 我想得到一个 return 对象数组,这可能吗?

我知道通常 Doctrine returns 是一个实体的对象,因为我有一个内部连接来从另一个 table 它 returns 数组中获取名称。

提前致谢。

   $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();

你可以使用这个:

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

或者这样:

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

只需像这样在 getResult() 上添加 \Doctrine\ORM\Query::HYDRATE_ARRAY

$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);

如果你想要对象数组,你必须设置实体之间的关系,并通过关系的拥有方创建查询。

示例:

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;

现在你必须查询关系的拥有方(邀请) 它将在字段 $invites

中保存所有与 Tourneys 的加入对象数据

它会为您提供对象数组。 基于您的查询

记住 setter $invites 为 setInvites(Tourney $invites) 和相反的关系 setTourneys(Invite $tourneys)

这种方式是不可能的。也就是说,你做错了。

你告诉 Doctrine return 包含一个实体和一个字符串的集合的集合,所以这就是你得到的。 Doctrine 不会以此为对象,因为它不知道如何滋润这样的结果。

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

如果您只想接收对象集合,则需要创建一个包含两个字段(相关实体和字符串 属性)的新实体,然后使用 ResultSet mapping补充水分。