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 字节(

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

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

$this->_categoryRepositoryMagentoCatalogModelCategoryRepository的一个实例

/**
* 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;
}

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

最新更新