首页 > 解决方案 > Magento 2:获取类别描述

问题描述

我正在尝试加载(子)类别的集合并显示它们的描述。

我尝试了以下事情(没有成功)。使用带有过滤器的集合来获取根类别。使用这种方法,只有根类别才能返回正确的描述。

$cats = $this->categoryFactory
    ->create()
    ->setStoreId(1)
    ->getCollection()
    ->addAttributeToFilter('url_key',$this->getData( 'root_category_id' ))
    ->addAttributeToSelect(['description', 'url_key', 'name', 'store_id']);

var_dump($cats->getFirstItem()->getDescription()); // THIS WORKS!

// iterate subcats
foreach($cats->getFirstItem()->getChildrenCategories() as $subCat) {
    var_dump($subCat->getDescription()); // NULL
}

我希望获得一个类别集合和过滤器,parent_id因为我认为这可能会起作用。但是我没有让它工作。我尝试了以下方法:

$cats = $this->categoryFactory
    ->create()
    ->setStoreId(1)
    ->getCollection()
    ->addAttributeToFilter('parent_id',$this->getCategory()->getId())
    ->addAttributeToSelect(['description', 'url_key', 'name', 'store_id']);

和:

$cats = $this->categoryFactory
    ->create()
    ->setStoreId(1)
    ->getCollection()
    ->addAttributeToSelect(['description', 'url_key', 'name', 'store_id']);
    ->getSelect()->where ("catalog_category_entity.parent_id = " . $this->getCategory()->getId());

当我尝试使用该集合时,PHP 会抛出此错误。我怀疑这是因为它想要加载太多类别?

收到错误“PHP 消息:PHP 致命错误:允许的 792723456 字节内存大小已用尽(尝试分配 400572416 字节)

我希望有人能引导我朝着正确的方向前进。

标签: phpmagento2

解决方案


这是我从一个旧项目中写的一个片段,很抱歉我没有专门为你测试它,但我知道它今天仍然存在于生产站点上。

$this->_categoryRepository是一个实例Magento\Catalog\Model\CategoryRepository

/**
 * Get child categories of parent category id.
 * @param int $parentId
 * @return array
 */
public function getChildren(int $parentId): array
{
    $parent = $this->_categoryRepository->get($parentId);
    $childIds = explode(',', $parent->getChildren(false, true, true));

    $children = [];

    if (empty($childIds)) {
        return $children;
    }

    foreach ($childIds as $i => $id) {
        $children[] = $this->_categoryRepository->get($id);
    }

    return $children;
}

您会注意到我使用的是类别存储库而不是工厂和集合。这个堆栈溢出问题有一些更深入的信息。


推荐阅读