Magento 2 通过商店查询获取类别

问题描述

我想从 Magento 2 数据库中的查询获取特定商店的所有启用类别。当我尝试从表 catalog_category_entity_int

进行数据库查询
SELECT * FROM `catalog_category_entity_int` WHERE `attribute_id`=46 AND `store_id`=1 GROUP BY `entity_id`

其中 46 是启用属性属性 ID。

通过这个查询,我得到了所有类别的 id,但是如果我更改 store_id,所有商店的类别都是相同的,所有商店的结果都相同,但我需要商店特定的类别,就像我在 magento 管理中看到的那样目录 > 类别部分。

解决方法

使用 \Magento\Store\Model\StoreManagerInterface 作为当前商店并将其应用到您的查询中

试试这个

protected $storeManager;

public function __construct(
    \Magento\Store\Model\StoreManagerInterface $storeManager,$data = []
) {
    $this->storeManager = $storeManager;
    parent::__construct($data);
}

$categoryFactory = $objectManager->create('Magento\Catalog\Model\ResourceModel\Category\CollectionFactory');
$categories = $categoryFactory->create()                              
    ->addAttributeToSelect('*')
    ->setStore($this->storeManager->getStore());

foreach ($categories as $category){
    $category->getId();
}