Search code examples
symfonywhere-indoctrine-querysylius

sylius how to get products by taxonomy?


I have an example tree.

| Brands
|-- SuperTees
|-- Stickypicky
|-- Mugland
|-- Bookmania

I can get all product by subcategories in Brands, but I can't get all products by Brands. Please, help create query


Solution

  • I solved this problem myself, but I'm not sure what did the right thing. I override controller and repository. It is my controller.

    use Symfony\Component\HttpFoundation\Request;
    use Sylius\Bundle\CoreBundle\Controller\ProductController as BaseProductController;
    use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
    use Sylius\Component\Taxonomy\Model\Taxon;
    
    class ProductController extends BaseProductController
    {
        public function indexByTaxonomyAction(Request $request, $permalink)
        {
            /** @var Taxon $taxon */
            $taxon = $this->get('sylius.repository.taxon')
                ->findOneByPermalink($permalink);
    
            if (!isset($taxon)) {
                throw new NotFoundHttpException('Requested taxon does not exist.');
            }
            $ids = array($taxon->getId());
    
            /** @var Taxon $child */
            foreach ($taxon->getChildren() as $child) {
                array_push($ids, $child->getId());
            }
    
    
            $paginator = $this
                ->getRepository()
                ->createByTaxonsPaginator($ids);
    
            $paginator->setMaxPerPage($this->config->getPaginationMaxPerPage());
            $paginator->setCurrentPage($request->query->get('page', 1));
    
            return $this->render(
                $this->config->getTemplate('indexByTaxonomy.html'),
                array(
                    'taxon' => $taxon,
                    'products' => $paginator,
                )
            );
        }
    } 
    

    it is my repository

    use Sylius\Bundle\CoreBundle\Doctrine\ORM\ProductRepository as BaseProductRepository;
    
    class ProductRepository extends BaseProductRepository
    {
    
        public function createByTaxonsPaginator(array $ids)
        {
            $queryBuilder = $this->getCollectionQueryBuilder();
    
            $queryBuilder
                ->innerJoin('product.taxons', 'taxon')
                ->andWhere('taxon.id IN ( :ids )')
                ->setParameter('ids', $ids)
            ;
    
            return $this->getPaginator($queryBuilder);
        }
    }