Question

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

Was it helpful?

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);
    }
} 

OTHER TIPS

If you're after the products for display/serialisation purposes, you can render an internal request to reuse the existing ProductController actions.

https://docs.sylius.com/en/1.12/cookbook/shop/embedding-products.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top