在 Doctrine2 实体的 ManyToMany 属性之间加入

Join between ManyToMany properties at Doctrine2 entities

我有这个表关系:

这是我的 messagesemails 实体的样子(我刚刚添加了重要信息):

class Message
{
    /**
     * @var Brand
     *
     * @ORM\ManyToOne(targetEntity="Brand")
     * @ORM\JoinColumn(name="brands_id", referencedColumnName="id")
     */
    protected $brand;

    ...

}


class Email
{
    /**
     * @ORM\ManyToMany(targetEntity="Message", inversedBy="messageXrefMail", cascade={"persist", "remove"})
     * @ORM\JoinTable(name="emails_messages_xref",
     *      joinColumns={@ORM\JoinColumn(name="emails_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="messages_id", referencedColumnName="id")}
     * )
     */
    protected $emailsMessageXref;

    ...
}

我需要获取与 email 相关的 brands,但我不知道在这种情况下该怎么做。主查询中包含一些表,我得到了这个:

public function findEmailValues($eid)
{
    $qb = $this->_em->createQueryBuilder();
    $qb->select('e.id', 'r.id')
        ->from('PDOneBundle:Email', 'e')
        ->leftJoin('PDOneBundle:Representative', 'r', \Doctrine\ORM\Query\Expr\Join::WITH, 'e.rep = r.id')
        ->leftJoin('PDOneBundle:Territory', 't', \Doctrine\ORM\Query\Expr\Join::WITH, 'r.territory = t.id')
        ->leftJoin('PDOneBundle:Target', 'tg', \Doctrine\ORM\Query\Expr\Join::WITH, 't.id = tg.territory')
        ->where('e.id = :eid')
        ->setParameter('eid', $eid);

    return $qb->getQuery()->getSingleResult();
}

但我不知道从那里去哪里。我可以得到一些构建 DQL 的帮助吗?

这应该有效:

    $qb->select('e.id', 'r.id', 'br')
        ->from('PDOneBundle:Email', 'e')
        ->leftJoin('PDOneBundle:Representative', 'r', \Doctrine\ORM\Query\Expr\Join::WITH, 'e.rep = r.id')
        ->leftJoin('PDOneBundle:Territory', 't', \Doctrine\ORM\Query\Expr\Join::WITH, 'r.territory = t.id')
        ->leftJoin('PDOneBundle:Target', 'tg', \Doctrine\ORM\Query\Expr\Join::WITH, 't.id = tg.territory')
        ->leftJoin('e.emailsMessageXref', 'me') // many to many on email -> messages
        ->leftJoin('me.brand', 'br') // many to one on message -> brand
        ->where('e.id = :eid')
        ->setParameter('eid', $eid);