php - 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->_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;
}
您会注意到我使用的是类别存储库而不是工厂和集合。这个堆栈溢出问题有一些更深入的信息。
推荐阅读
- c# - NET C# - 如何通过 dynamodb 中的映射值在带有条件表达式的列表中设置嵌套映射?
- node.js - nodejs firebase firestore - 加载用户代码时函数失败。错误消息:错误:请检查您的功能日志?
- javascript - 导出默认功能反应原生
- docker - 多阶段构建中的最终输出图像是什么?
- macos - 如何在表格视图中选择一行?
- oracle - oracle 11g数据库如何安装dbms_defer系统包?
- python - 如何为子图放置两个图例?
- postgresql - 如果黑客复制数据库文件,是否有可能读取 Postgres 数据库中的数据?
- python - 我如何遍历文件夹中的每个 csv 文件,选择每个文件的某些列并将其与已经存在的 .csv 文件合并
- angular - Angular + Nestjs 部署