查询生成器中的复杂查询

时间:2012-06-02 21:03:25

标签: php symfony doctrine-orm

如何在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的新手。我阅读了整个文档但是找不到这样复杂的例子实际上我对querybuilder如何构建查询有点困惑。如果你用简单的话解释一下它会很棒

提前致谢

2 个答案:

答案 0 :(得分: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();

多数民众赞成:)

答案 1 :(得分: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();