Symfony 3 - 本机查询以获取表单中 EntityType 的选项

Symfony 3 - Native query to fetch options for EntityType in form

我有一个表单,其中有一个字段连接到实体:

->add('category', EntityType::class, array(
                'class' => ProductCategory::class,
                'required' => true,
                'query_builder' => function(ProductCategoryRepository $repo) {
                    return $repo->createCategoryStructuredQuery();
                }
            ))

但是在回购中我必须使用以下查询:

SELECT c.* FROM product_category c order by coalesce(c.parentid, c.id), c.parentid is not null, c.name

Doctrine 抛出异常,因为 coalesce and is not null in 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
            );
}

如何 return QueryBuilder 实例将其正确分配给表单字段?或者我如何使用查询构建器正确构建上述原则查询?

正如我看到的代码,Doctrine 的异常只是一个开始。你的函数没有 return 任何值,尽管它应该。其次,您必须对您创建的 $nativeQuery 变量执行 getResult() 方法。第三,即使您 return 编辑了 getResult() 方法的结果,它仍然不是一个 queryBuilder 对象(正如表单中的回调所期望的那样)而是一个数组。

你为什么不留在回调函数里面 return:

return $repo->createQueryBuilder('c')
    // here build your query with qb functions, e.g. ->orderBy(arg1 [, arg2])

您可以直接在查询生成器中使用 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();
    }
));