Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magento : Category Name instead of category ids in category path.

I am trying to get category names in category path based on product id in magento.

Suppose My Product Id = 1 and In that I define category5 (id = 5) and I get category path like 2/3/5. Instead of this type of category path I need category path like category2/category3/category5. That means I need category names in path Instead of category Ids. I got this by using following code but its takes so much time. I need to reduce processing time.

Please give me suggestions for how can I reduce process time.

$category_model = Mage::getModel('catalog/category');  
$product_model = Mage::getModel('catalog/product'); 
$all_cats = array();
$product_model->reset();
$_product = $product_model->load($entityId);
$all_cats = $product_model->getCategoryIds($_product); 
$main_cnt = count($all_cats);
$cat_str_main = ''; 
$j = 0;
foreach($all_cats as $ac)
{
    $root_category = $category_model->load($ac);
    $cat_path = $root_category->getPath();
    $cat_arr = explode("/",$cat_path);
    $cnt = count($cat_arr);
    $cat_str = '';
    $main_str = '';
    $i=0;
    foreach($cat_arr as $ids)
    {
                $root_category = $category_model->load($ids); //load root catalog
        if($i == 2)
        {
            $cat_str = $category_model->getName();
        }
        else if($i > 2)
        {
            $cat_str = $cat_str."/".$category_model->getName();
        }
        $i = $i+1;
    }
    if($j < 1)
    {
        $cat_str_main = $cat_str;
    }
    else 
    {
        $cat_str_main = $cat_str_main .",".$cat_str;
    }
    $j = $j+1;
}

Thanks.....

like image 799
user123 Avatar asked Dec 26 '22 12:12

user123


1 Answers

You should use the category collection instead of load for each category to reduce the database queries.

Edit: I have written you a code sample. I assume you have the category ID of the category of which you want to get the names of the path as $categoryId:

$category = Mage::getModel('catalog/category')->load($categoryId);
$collection = $category->getResourceCollection();
$pathIds = $category->getPathIds();
$collection->addAttributeToSelect('name');
$collection->addAttributeToFilter('entity_id', array('in' => $pathIds));
$result = '';
foreach ($collection as $cat) {
    $result .= $cat->getName().'/';
}
like image 173
mpaepper Avatar answered Mar 02 '23 01:03

mpaepper