首页 > 解决方案 > 如何通过 id 获取自定义类别属性:Magento 2

问题描述

我有类别 ID,需要获取所有自定义属性,例如缩略图。

我的代码没有返回所有属性

$category = $this->categoryRepository->get($childId, $this->_storeManager->getStore()->getId());
$category->getData();

标签: magento2custom-attribute

解决方案


您可以使用 Category 的类并通过在方法中CollectionFactory使用star (*)符号来选择所有属性。addAttributeToSelect您可以在课堂上使用下面的代码示例。

protected $_categoryFactory;

public function __construct(
    // ...
    \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $collecionFactory,
    ) {
        // ...
        $this->_categoryFactory = $collecionFactory;
}

public function yourFunctionName()
{
    $catId = 3; // your category id        
    $collection = $this->_categoryFactory
                    ->create()
                    ->addAttributeToSelect('*')
                    ->addAttributeToFilter('entity_id',['eq'=>$catId])
                    ->setPageSize(1);

    $catObj = $collection->getFirstItem();
    $thumbnail = $catObj->getThumbnail(); // it should return value if attribute name is thumbnail
    $catData = $catObj->getData(); // dump this line to check all data

    // ...
}

推荐阅读