Doctrine QueryBuilder使用子查询复杂的非表查询

时间:2017-05-17 12:07:12

标签: php symfony doctrine-orm query-builder

我想用symfony / Doctrine2 QueryBuilder构建一个SQL查询。

select     
(SELECT group_concat(DISTINCT sender)       
    FROM transactions) as senders,
(SELECT group_concat(DISTINCT receiver) 
    FROM transactions) as receivers, 
(SELECT group_concat(DISTINCT message_type) 
    FROM transactions) as types

如上面的描述所示,主查询没有表

有没有办法在Querybuilder中实现它,而无需编写显示的SQL命令?

1 个答案:

答案 0 :(得分:0)

根据:

  

与构建普通Query一样,您构建一个QueryBuilder对象,只提供正确的方法名称。以下是如何构建QueryBuilder对象的示例:

//$em instanceof EntityManager
// example1: creating a QueryBuilder instance
$qb = $em->createQueryBuilder();`

http://doctrine-orm.readthedocs.io/en/latest/reference/query-builder.html#constructing-a-new-querybuilder-object

但这需要您的根查询针对实体进行映射。查询编译器也没有为子查询提供任何真正的支持,但是有一些关于如何实现的例子:

// build root query
$query = Doctrine_Query::create()
  ->from('Movie m')
  ->where('name = ?', 'Prometheus')
;

// build subquery
$subquery = $query->createSubquery()
  ->from('SeenMovie sm')
  ->where('m.name = sm.name')
;

// nest subquery and execute
$query->where('EXISTS (' . $subquery->getDql() . ')')->execute();

借鉴:https://www.philipphoffmann.de/2012/08/29/a-bulletproof-pattern-for-creating-doctrine-subqueries-of-any-complexity/