I need to get product collection by filter multiple category ids in magento 2
-
02-03-2021 - |
Frage
I need to get product collection by filter multiple category ids.
Here is my code:
$catId = [2, 3, 5];
$productcollection = $objectmanager->create('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$categoryProducts = $productcollection->addAttributeToSelect('*')
->addAttributeToSort('position', 'ASC')
->addCategoriesFilter(['in' => $catId])
->addAttributeToFilter('color', ['in', $colorValues]);
But this code is not working.
Lösung
Actually you pass the category ids array in addCategoriesFilter(['in' => $cat_ids])
that's why the error occur. Just Replace my code with your's
$cat_ids = "2,3,5";
$productcollection = $objectmanager->create('Magento\Catalog\Model\ResourceModel\Product\Collection');
$categoryProducts = $productcollection->addAttributeToSelect('*')->addAttributeToSort('position', 'ASC')->addCategoriesFilter(['in' => $cat_ids])->addAttributeToFilter('color', array('in',$colorvalues));
I hope this will help
Andere Tipps
You can add the other attribute filter. I just check multiple category filter. It is working, I just Created object again after loading model collection.
$productcollection = $obj->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory')->create();
$cat_ids = [179,109];
$categoryProducts = $productcollection->addAttributeToSelect('*');
$categoryProducts->addCategoriesFilter(array('in' => $cat_ids));
echo '<pre>';
echo count($categoryProducts);
//var_dump($categoryProducts);
foreach ($categoryProducts as $product) {
print_r($product->getData());
}
echo '</pre>';
protected $_productCollectionFactory;
public function __construct(
\Magento\Framework\App\Helper\Context $context,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory
) {
parent::__construct($context);
$this->_productCollectionFactory = $productCollectionFactory;
}
public function getProductCollectionByCategories()
{
$categories = [2,3,5];//category ids array
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addCategoriesFilter(['in' => $categories]);
return $collection;
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit magento.stackexchange