Magento – Excluding category by entity_id from the collection of categories

categorycollection;

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 :)!

Best Answer

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));
Related Topic