我有一个表单,其中一个字段连接到entity:
->add('category', EntityType::class, array(
'class' => ProductCategory::class,
'required' => true,
'query_builder' => function(ProductCategoryRepository $repo) {
return $repo->createCategoryStructuredQuery();
}
))但是,在repo中,我必须使用以下查询:
SELECT c.* FROM product_category c order by coalesce(c.parentid, c.id), c.parentid is not null, c.name由于coalesce和is not null在order子句中存在异常,所以我在createCategoryStructuredQuery()中创建了一个原生查询:
public function createCategoryStructuredQuery() {
$rsm = new ResultSetMapping();
$rsm->addEntityResult('ProductBundle\Entity\ProductCategory', 'c');
$nativeQuery = $this->getEntityManager()
->createNativeQuery(
'SELECT c.*
FROM product_category c
order by coalesce(c.parentid, c.id),
c.parentid is not null,
c.name',
$rsm
);
}如何返回QueryBuilder实例以将其正确分配给表单域?或者,我如何使用查询构建器正确地构建上述原理查询?
发布于 2018-01-21 09:09:07
您可以在查询生成器中直接使用COALESCE。实际上,您只需将其添加到SELECT语句中,然后将其用于排序。您需要做的是将该字段声明为HIDDEN,以便从最终结果中排除它。
->add('category', EntityType::class, array(
'class' => ProductCategory::class,
'required' => true,
'query_builder' => function(ProductCategoryRepository $repo) {
return $repo->createQueryBuilder('pc')
->select('pc, COALESCE(pc.parentid, pc.id) as HIDDEN orderId, -pc.parentId AS HIDDEN inverseParentId')
->orderBy('orderId', 'ASC')
->addOrderBy('inverseParentId', 'DESC')
->addOrderBy('pc.name', 'ASC')
->getQuery()->getResult();
}
));发布于 2018-01-21 07:33:45
正如我所看到的代码,Doctrine的异常只是个开始。您的函数不会返回任何值,尽管它应该返回。其次,您必须对您创建的$nativeQuery变量执行getResult()方法。第三,即使您返回getResult()方法的结果,它仍然不是一个queryBuilder对象(正如表单中的回调所期望的那样),而是一个数组。
为什么不直接在回调函数中返回:
return $repo->createQueryBuilder('c')
// here build your query with qb functions, e.g. ->orderBy(arg1 [, arg2])https://stackoverflow.com/questions/48358603
复制相似问题