我尝试通过it url_key在Magento2.0中获得一个类别。
现在我得到了:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$categoryFactory = $objectManager->create('Magento\Catalog\Model\CategoryFactory');
$category = $categoryFactory->create()
->addAttributeToFilter('url_key','my_category_url_key');
它返回这个错误:
错误筛选模板:无效的方法Magento\Catalog\Model\Category\Interceptor::addAttributeToFilter(Array ( => url_key 1 => my_category_url_key )
谢谢。
发布于 2017-02-01 16:05:15
/**
* @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());
发布于 2018-06-29 17:46:29
我知道这是个老生常谈的问题,但如果有人想知道的话...
这里的所有答案都使用ObjectManager。这是一种糟糕的做法。实现这一点的正确方法如下:
namespace Vendor\Module\Model;
use Magento\Catalog\Model\CategoryFactory;
class MyClass {
private $categoryFactory;
public function __construct(
CategoryFactory $categoryFactory
} {
$this->categoryFactory = $categoryFactory;
}
public function MyFunction() {
$categoryFactory = $this->categoryFactory->create();
$category = $categoryFactory->loadByAttribute('url_key', 'my_category_key');
$categoryId = $category->getId(); // E.g. if you want the ID.
}
这将返回URL-key为'my_ category _key‘的类别的对象。
发布于 2016-01-28 19:58:20
addAttributeToFilter
是一种集合方法。
您应该在类别集合上执行,而不是在类别实例上执行。
https://stackoverflow.com/questions/35058261
复制相似问题