我如何获得产品所属的类别id,该类别id相对于我当前所在的商店


How do I get the category ids that a product is in with respect to the store that I'm currently on

我在一个产品页面上,有产品对象但当我试图使用:

获取类别id时
$_product->getCategoryIds();

或:

$_product->getResource()->getAttribute('category_ids')->getFrontend()->getValue($_product); 

它得到了所有的类别id,我只想要我所在商店的类别id。

这是一个多商店的环境,所以我的问题。其他一切看起来都很好,分类列表也很好。这是我唯一的问题。有人能帮忙吗?

与alan的回答非常相似,可能循环少一点:

$rootCategory = Mage::getModel('catalog/category')
    ->load(Mage::app()->getStore()->getRootCategoryId());
$sameStoreCategories = Mage::getResourceModel('catalog/category_collection')
    ->addIdFilter($product->getCategoryIds())
    ->addFieldToFilter('path', array('like' => $rootCategory->getPath() . '/%'))
    ->getItems();
var_dump(array_keys($sameStoreCategories));

这总是有效的。令人讨厌的是,您仍然需要加载类别。

如果启用了平面分类表,则可以使用以下变体:

$sameStoreCategories = Mage::getResourceModel('catalog/category_flat_collection')
    ->addIdFilter($product->getCategoryIds())
    ->getItems();
var_dump(array_keys($sameStoreCategories));

为什么它工作?因为平面表是按存储索引的,并且每个平面表只包含与该存储组根类别相关联的类别实体记录。

因此,即使您按照与产品关联的所有类别id进行过滤,该集合也将只包含当前商店中存在的类别。

如果您有数百万个类别或数百万个产品,或者需要收集所有产品的所有类别-您可以尝试下一个怪胎方式(同样只适用于类别平坦索引重建):

  • 在某些安装程序或cron中创建一个新表,并使其与下一个请求保持同步

:

CREATE TABLE IF NOT EXISTS categories_X SELECT product_id, CONVERT(GROUP_CONCAT(category_id) USING utf8) as category_id FROM catalog_category_product where category_id in (select entity_id from catalog_category_flat_store_X) GROUP BY product_id
  • 其中X -为商店ID

  • 再次编写模型或直接请求以获取所需商店和所需产品的所有类别

这个有点棘手,所以如果下面的代码不起作用,可能是代码的问题,而不是你的问题。

问题是,据我所知,Magento不跟踪哪些类别在哪个商店。相反,Magento会跟踪特定存储的根类别

这意味着一旦我们有了一个类别id列表,我们需要获取每个类别的根类别,然后检查该根类别是否与当前存储的根类别匹配。

下面的代码应该做到这一点,但请用各种产品测试

    //get root category for current store
    $store_root_id = Mage::app()->getStore()->getRootCategoryId();
    //get category IDs from product
    $ids = $product->getCategoryIds();        
    //load full cateogires
    $categories = Mage::getModel('catalog/category')
    ->getCollection()
    ->addIdFilter($ids);
    //filter out categories with different root
    $category_ids = array();
    foreach($categories as $cat)
    {
        //path property is 1/root_id/id/id
        $parts      = explode('/', $cat->getPath());
        $one        = array_shift($parts);
        $root_id    = array_shift($parts);
        if($root_id == $store_root_id)
        {
            $category_ids[] = $cat->getId();    
        }            
    }
    var_dump($category_ids);