2

如何在 Symfony 2 中使用 QueryBuilder 执行此查询

SELECT um.id, sv.patentgroup_id, pm.portfolio_id, pp.id
FROM sv_patents sv
LEFT JOIN pm_patentgroups pm ON sv.patentgroup_id = pm.id
LEFT JOIN pm_portfolios pp ON pm.portfolio_id = pp.id
LEFT JOIN um_users um ON pp.user_id

实体类中的关联定义为

在 SvPatents 我有

 /**
 * @var PmPatentgroups
 *
 * @ORM\ManyToOne(targetEntity="PmPatentgroups")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="patentgroup_id", referencedColumnName="id")
 * })
 */
private $patentgroup;

在 PmPatentgroups 我有

/**
 * @var PmPortfolios
 *
 * @ORM\ManyToOne(targetEntity="PmPortfolios")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="portfolio_id", referencedColumnName="id")
 * })
 */
private $portfolio_id;

在 PmPortfolios 我有

/**
 * @var UmUsers
 *
 * @ORM\ManyToOne(targetEntity="UmUsers")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="user_id", referencedColumnName="id")
 * })
 */
private $user;

我试过了,但它给了我表格中的整个结果,看起来连接工作不正常

$repository = $this->getDoctrine()->getRepository('MunichInnovationGroupBundle:SvPatents');
        $qb = $repository->createQueryBuilder('sv')
        ->leftJoin('sv.patentgroup','pm')
        ->leftJoin('pm.portfolio_id','pp')
        ->leftJoin('pp.user','um')
        ->getQuery();
        $patents = $qb->getArrayResult();

我对 Symfony2 和 Doctorine2 很陌生。我阅读了整个文档,但实际上找不到如此复杂的示例,我对查询构建器如何构建查询感到有些困惑。如果你用简单的话解释一下就好了

提前致谢

4

2 回答 2

2

我找到了解决我的问题的方法。如果您在表中查找特定用户的记录,那么您需要添加一个 where 子句。这就是您的查询的样子

$user_id = 1;
        $repository = $this->getDoctrine()->getRepository('MunichInnovationGroupBundle:SvPatents');
        $qb = $repository->createQueryBuilder('sv')
        ->select('sv')
        ->leftJoin('sv.patentgroup','pm')
        ->leftJoin('pm.portfolio_id','pp')
        ->leftJoin('pp.user','um')
        ->where('pp.user = :user_id')
        ->setParameter('user_id', $user_id)
        ->getQuery();
        $patents = $qb->getArrayResult();

就这样 :)

于 2012-06-02T21:44:55.223 回答
0

你很亲密。您只需要添加一个->select()查询部分:

$repository = $this->getDoctrine()->getRepository('MunichInnovationGroupBundle:SvPatents');
$qb = $repository->createQueryBuilder('sv')
                 ->select('um.id, pm.id, pp.id') // add this part
                 ->leftJoin('sv.patentgroup','pm')
                 ->leftJoin('pm.portfolio_id','pp')
                 ->leftJoin('pp.user','um')
                 ->getQuery();
$patents = $qb->getArrayResult();
于 2012-06-02T21:18:34.613 回答