学说查询构建器,其中元素是学说嵌套集树父级的子级

问题描述 投票:0回答:1

我想构建一个查询构建器,它返回在某个时刻在其父级中具有给定元素的元素。

在父级上加倍或使用 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();

当然,如果父母不是根父母,祖父母也不是父母,这就不再起作用了。

我该怎么办?

php symfony tree doctrine nested-sets
1个回答
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;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.