use*_*123 4 php performance magento magento-1.7
我试图根据magento中的产品ID在类别路径中获取类别名称.
假设我的产品ID = 1,并且我定义了category5(id = 5),我得到类别路径,如2/3/5.我需要类别路径,如category2/category3/category5,而不是这种类型的路径.这意味着我需要路径中的类别名称而不是类别ID.我通过使用以下代码得到了这个,但它花了很多时间.我需要减少处理时间.
请告诉我如何减少处理时间的建议.
$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;
}
Run Code Online (Sandbox Code Playgroud)
谢谢.....
您应该为每个类别使用类别集合而不是加载来减少数据库查询.
编辑:我给你写了一个代码示例.我假设您有类别ID,您想要获取路径名称为$ 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().'/';
}
Run Code Online (Sandbox Code Playgroud)