嗨,我想在 magento 2.3 中加载多个类别 ID。
我尝试了下面的代码,但它只获取子类别的第一个类别,而不是该类别的其余部分。
$categories = $_objectManager->create('Magento\Catalog\Model\Category')->load(3,4,5);
嗨,我想在 magento 2.3 中加载多个类别 ID。
我尝试了下面的代码,但它只获取子类别的第一个类别,而不是该类别的其余部分。
$categories = $_objectManager->create('Magento\Catalog\Model\Category')->load(3,4,5);
Magento 2 禁止直接使用ObjectManager
( https://devdocs.magento.com/guides/v2.3/extension-dev-guide/object-manager.html )。
CollectionFactory
您应该通过在类构造函数中注入 a 来使用依赖注入来获取资源集合来查询类别。这是一个生成的类,因此您只需在构造函数参数中对其进行类型提示(bin/magento setup:di:compile
之后可能需要运行)。
带有类型提示的集合工厂的构造函数示例:
private $categoryCollectionFactory;
public function __construct(
\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory
) {
$this->categoryCollectionFactory = $categoryCollectionFactory;
}
然后,在您的方法中,您可以获得资源集合的实例并将 ID 添加到过滤器,之后您可以获得类别模型。
public function someMethod()
{
// get an instance of CategoryCollection
$categoryCollection = $categoryCollectionFactory->create();
// add a filter to get the IDs you need
$categoryCollection->addFieldToFilter('entity_id', [3, 4, 5]);
// either call getItems() and iterate over it, or do whatever you need
foreach ($categoryCollection->getItems() as $category) {
/** @var \Magento\Catalog\Model\Category\Interceptor $category */
// get the category data
var_dump($category->getData());
}
}