0

I'm trying to filter my product collection by tier price.

I currently have this code but it doesn't work and it returns error:

protected $_productCollectionFactory;
        
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,        
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,        
        array $data = []
    )
    {    
        $this->_productCollectionFactory = $productCollectionFactory;    
        parent::__construct($context, $data);
    }

public function getProductCollectionTot()
    {
        $collection = $this->_productCollectionFactory->create();
        $collection->addAttributeToSelect('*');
        
        
        $collection->getSelect()->join('catalog_product_entity_tier_price as tier', 'price_index.entity_id = tier.entity_id');

        $collection->addFinalPrice()
              ->addMinimalPrice()
              ->getSelect()
              ->where('tier.all_groups = 0')
              ->where('price_index.Tier_price < price_index.price');
              
        return $collection;
    }

How can I filter my collection by tier price?

1

You have missed joining product collection with catalog_product_index_price table. Please make changes in your query as follows:

    public function getProductCollectionTot() {
        $collection = $this->_productCollectionFactory->create();
        $collection->addAttributeToSelect('*');

        $collection->getSelect()->join('catalog_product_index_price as price_index', 'e.entity_id = price_index.entity_id');    // Add this join statement
        $collection->getSelect()->join('catalog_product_entity_tier_price as tier', 'price_index.entity_id = tier.entity_id');

        $collection->addFinalPrice()
            ->addMinimalPrice()
            ->getSelect()
            ->where('tier.all_groups = 0')
            ->where('price_index.Tier_price < price_index.price');

        return $collection;
    }

Hope this may help you. Please let me know if it worked for you or not. Happy to Help :)

2
  • Man, now works!! The issue was in last "->where". I fixed from ->where('price_index.Tier_price < price_index.price'); to ->where('tier.value < price_index.price'); Thanks for the help ;) – Jackom May 19 at 17:21
  • Only problem: When I try to create foreach it goes into error and tells me: "Item (Magento \ Catalog \ Model \ Product \ Interceptor) with the same ID" 42 "already exists". How can i do for fix this issue? This happen when join the two tables... – Jackom May 19 at 17:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.