2

I need to exclude a single category from a collection of categories. The code I use to get the collection:

$layer = Mage::getSingleton('catalog/layer');
$_category = $layer->getCurrentCategory();
$_parent_category = $_category->parent_category;
$_grandparent_cat = $_parent_category->getParentCategory(); 
$eid = $_parent_category->entity_id;

and now the code I use to filter the categories

$_new_categories = $_grandparent_cat
    ->getChildrenCategories()
    ->addAttributeToSelect("*")
    ->addAttributeToFilter('entity_id', array('neq'=>$eid));

This should take all child categories of the grandpared_cat and return them, excluding the current cat(the one with $eid) but it returns all subcategories. How can I solve this? Thanks :)!

2
  • nin used instead of neq
    – Amit Bera
    Commented Jan 19, 2015 at 14:40
  • Hi Amit. Unfortunately 'nin' doesn't work either.
    – Alan
    Commented Jan 19, 2015 at 14:43

1 Answer 1

4

Mage_Catalog_Model_Resource_Category::getChildrenCategories returns a loaded collection, so your filter does not get applied.

public function getChildrenCategories($category)
{
    $collection = $this->_getChildrenCategoriesBase($category);
    $collection->addAttributeToFilter('is_active', 1)
        ->addIdFilter($category->getChildren())
        ->load();

    return $collection;
}

protected function _getChildrenCategoriesBase($category)
{
    $collection = $category->getCollection();
    $collection->addAttributeToSelect('url_key')
        ->addAttributeToSelect('name')
        ->addAttributeToSelect('all_children')
        ->addAttributeToSelect('is_anchor')
        ->setOrder('position', Varien_Db_Select::SQL_ASC)
        ->joinUrlRewrite();
    return $collection;
}

I'm not sure the best way to proceed as _getChildrenCategoriesBase is a protected method. This might be the type of collection you could create if it was not a protected method

    //base methods
    $_new_categories = Mage::getResourceModel('catalog/category_collection');
    $_new_categories->addAttributeToSelect('url_key')
        ->addAttributeToSelect('name')
        ->addAttributeToSelect('all_children')
        ->addAttributeToSelect('is_anchor')
        ->setOrder('position', Varien_Db_Select::SQL_ASC)
        ->joinUrlRewrite();

    //children methods
    $_new_categories->addAttributeToFilter('is_active', 1)
        ->addIdFilter($_grandparent_cat->getChildren());

    //your methods
    $_new_categories
        ->addAttributeToSelect('*')
        ->addAttributeToFilter('entity_id', array('neq' => $eid));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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