我正在尝试加载一个(子)类别的集合并显示它们的描述。
我尝试了以下几种方法(但没有成功)。使用带筛选器的集合获取根类别。使用此方法,只有根类别返回正确的描述。
$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字节)
我希望有人能把我引向正确的方向。
发布于 2019-08-26 20:35:52
下面是我从一个旧项目中写的一个片段,很抱歉,我还没有专门为您测试过它,但我知道它今天仍然在生产站点上运行。
$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;
}您会注意到,我使用的是类别存储库,而不是工厂和集合。This stack overflow question对此有更深入的了解。
https://stackoverflow.com/questions/57659343
复制相似问题