编程语言
首页 > 编程语言> > php-Magento 2如何通过url_key获取类别

php-Magento 2如何通过url_key获取类别

作者:互联网

我尝试通过url_key在Magento 2.0中获得一个类别.

现在我有:

        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $categoryFactory = $objectManager->create('Magento\Catalog\Model\CategoryFactory');
        $category = $categoryFactory->create()
            ->addAttributeToFilter('url_key','my_category_url_key');

它返回我这个错误:

Error filtering template: Invalid method
Magento\Catalog\Model\Category\Interceptor::addAttributeToFilter(Array
( [0] => url_key [1] => my_category_url_key ) )

谢谢.

解决方法:

/**
 * @var \Magento\Catalog\Model\CategoryFactory
 ****** inject in constructor ******
 */
protected $categoryFactory;

---------
---------
---------
$categories = $this->categoryFactory->create()
            ->getCollection()
            ->addAttributeToFilter('url_key','devops')
            ->addAttributeToSelect(['entity_id']);
echo "<pre>";
print_r($categories->getFirstItem()->getEntityId());

标签:magento2,php
来源: https://codeday.me/bug/20191119/2033610.html