Doctrine querybuilder其中element是一个doctrine嵌套集树父的子节点

时间:2015-01-22 15:01:52

标签: symfony doctrine-orm tree doctrine nested-sets

我想构建一个querybuilder,它返回在父元素中具有某个给定元素的元素。

在父级或使用root上加倍是不正确的,因为可能有多个级别。

到目前为止,我有这段代码:

return = $this
        ->createQueryBuilder('o')
        ->leftJoin('o.organizationCategories', 'c')
        ->leftJoin('c.parent', 'parent')
        ->where('parent = ?2')
        ->orWhere('parent.parent = ?2')
        ->setParameter(2, $parent)
        ->getQuery()
        ->getResult();

当然,如果父母不是根父母,祖父母不是父母,那么这不再适用。

我该怎么办?

1 个答案:

答案 0 :(得分:0)

我最终做了以下

/**
 * ProductRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
abstract class HasCategoryRepository extends EntityRepository
{

    /**
     * @return QueryBuilder
     */
    abstract function getExplorerQueryBuilder();

    /**
     * Filters products on ingredients, which belong to the category 'consommable'
     *
     * @param ObjectCategory $objectCategory
     * @throws \Exception
     * @return \Doctrine\ORM\QueryBuilder
     */
    public function findByTopCategoryQueryBuilder($objectCategory)
    {
        $objectCategoryRepository = $this->_em->getRepository('AppBundle:Core\ObjectCategory');

        if (!$objectCategory instanceof ObjectCategory) $objectCategory=$objectCategoryRepository->findOneBy(array('slug' => $objectCategory));
        if (!$objectCategory) throw new \Exception("La catégorie n'a pas été trouvée.");

        $queryBuilder = $this->getExplorerQueryBuilder();

        $categories = array_merge(array($objectCategory), $objectCategoryRepository->children($objectCategory));
        $categoriesIds = array_map(function(BaseCategoryClass $category){return $category->getid();}, $categories);

        $queryBuilder = $queryBuilder
                ->andWhere($this->createQueryBuilder('object')->expr()->in('c.id', $categoriesIds))
            ;

        return $queryBuilder;
    }
}