我尝试通过 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');
Run Code Online (Sandbox Code Playgroud)
它返回给我这个错误:
过滤模板错误:无效方法 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());
Run Code Online (Sandbox Code Playgroud)
我知道这是一个老问题,但如果有人想知道......
这里的所有答案都使用 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.
}
Run Code Online (Sandbox Code Playgroud)
在此示例中,category将包含 URL 键为“my_category_key”的类别的对象。
| 归档时间: |
|
| 查看次数: |
15166 次 |
| 最近记录: |