When I foreach my collection filtered by tier price, qty and customer group I get the error: "Item (Magento \ Catalog \ Model \ Product \ Interceptor) with the same ID already exists".
This is my class:
namespace Vendor\Module\Block;
class ProductCollection extends \Magento\Framework\View\Element\Template
{
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 getProductCollectionSearch() {
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->setPageSize(3);
$collection->getSelect()->join('catalog_product_index_price as price_index', 'e.entity_id = price_index.entity_id');
$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('tier.qty = 1000')
->where('tier.value <= 0.20');
return $collection;
}
}
This problem arises when I try to foreach product in my phtml file. This is my phtml file:
<?php
$blockProductColl = $block->getLayout()->createBlock('\Vendor\Module\Block\ProductCollection');
$collectionSearch = $blockProductColl->getProductCollectionSearch();
$count=0;
//echo $collectionSearch->getSize();
foreach($collectionSearch as $itemSearch){
echo $itemSearch->getSku().'<br/>';
$count++;
}
?>
Is there a way to exclude duplicate Item IDs before foreaching the collection? Thanks!
SOLUTION:
public function getProductCollectionSearch() {
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToFilter('visibility', 4);
//$collection->setPageSize(10);
$joinConditions = 'e.entity_id = tier.entity_id';
$collection->getSelect()->join(
'catalog_product_entity_tier_price as tier',
$joinConditions
)
->where('tier.customer_group_id = 0')
->where('tier.qty = 1000')
->where('tier.value <= 0.10')
->where('tier.website_id = 0');
return $collection;
}