There is an array of category ids i.e. array(18,19,25);
I want to get those products which has all these categories from above array. Product should present in 18,19 and 25.
Array values can be anything i.e. category ids.
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this communityThere is an array of category ids i.e. array(18,19,25);
I want to get those products which has all these categories from above array. Product should present in 18,19 and 25.
Array values can be anything i.e. category ids.
Let's Assume you have categoryIds Array
$categories = array(18,19,25);
First You have to do category join
$collection->joinField(
'category_id', 'catalog/category_product', 'category_id',
'product_id = entity_id', null, 'left'
);
Now add simple IN
condition of collection
$pCollection->addAttributeToFilter('category_id', array('in' => implode(',', $categories)));
try
$productCollection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('category_id', array('in' => array('finset' => '18','19','25')));
uncaught Mage_Eav_Exception: Invalid attribute name: category_id
Sep 27, 2018 at 12:43
This can be a bit scary but is working fine for me, with:
// An array of category ids
$categoryIds = [18,19,25];
// Get a collection of products
$collection = Mage::getModel('catalog/product')->getCollection();
// Add a filter for each category: only products belonging to each
// category will be in the collection
$i = 1;
foreach ($categoryIds as $categoyId) {
$collection->joinField(
"category_product_${i}",
'catalog/category_product',
null,
'product_id=entity_id',
"{{table}}.category_id=${categoyId}",
'inner'
);
$i++;
}
// Set distinct (avoid duplicate products)
$collection->distinct(true);
Please try it
$catIds = array('10','82');
$productCollection =
Mage::getResourceModel('catalog/product_collection')
->setStoreId(0)
->joinField('category_id', 'catalog/category_product', 'category_id',
'product_id=entity_id', null, 'left')
->addAttributeToFilter('category_id', array('in' => array('finset' =>
$catIds )))
->addAttributeToSelect('*');
$productCollection->getSelect()->group('product_id')->distinct(true);
$collection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSort('created_at', 'DESC')
->load();
foreach ($collection as $product){
echo $product->getId().'</br>';
echo $product->getName().'</br>';
}
$products = Mage::getResourceModel('catalog/product_collection');
foreach($category_ids as $id)
$products->addCategoryFilter(Mage::getModel('catalog/category')->load($id));
UPDATE: this answer is wrong - it will filter the collection by the last category from $category_ids
array - addCategoryFilter
method doesn't support stacking. I didn't know that - what is the point of making a filter that supports only one category?