首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Magento 2:获取类别描述

Magento 2:获取类别描述
EN

Stack Overflow用户
提问于 2019-08-26 13:57:21
回答 1查看 2.1K关注 0票数 1

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

我尝试了以下几种方法(但没有成功)。使用带筛选器的集合获取根类别。使用此方法,只有根类别返回正确的描述。

代码语言:javascript
复制
$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获得一个类别集合和筛选器,因为我认为这可能有效。不过,我不想让它起作用。我尝试了以下方法:

代码语言:javascript
复制
$cats = $this->categoryFactory
    ->create()
    ->setStoreId(1)
    ->getCollection()
    ->addAttributeToFilter('parent_id',$this->getCategory()->getId())
    ->addAttributeToSelect(['description', 'url_key', 'name', 'store_id']);

和:

代码语言:javascript
复制
$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字节)

我希望有人能把我引向正确的方向。

EN

回答 1

Stack Overflow用户

发布于 2019-08-26 20:35:52

下面是我从一个旧项目中写的一个片段,很抱歉,我还没有专门为您测试过它,但我知道它今天仍然在生产站点上运行。

$this->_categoryRepositoryMagento\Catalog\Model\CategoryRepository的一个实例

代码语言:javascript
复制
/**
 * 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;
}

您会注意到,我使用的是类别存储库,而不是工厂和集合。This stack overflow question对此有更深入的了解。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57659343

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档