¿Cómo obtengo el category_id (o el Magento\Catalog\Model\Category) de la categoría raíz de una tienda determinada en Magento 2 desde un modelo personalizado?
En Magento 1.x, simplemente habría usado
Mage::app()->getStore($storeId)->getRootCategoryId();He intentado obtener el objeto Store del StoreManager, pero no puedo encontrar ninguna documentación para la categoría raíz.
Encontré la respuesta yo mismo. :-)
En \Magento\Store\Model\Store , hay una función getRootCategoryId()
namespace Vendor\Module\Helper; public class Store { /** * @var \Magento\Store\Model\StoreManagerInterface $storeManager */ protected $storeManager; public function __construct(\Magento\Store\Model\StoreManagerInterface $storeManager) { $this->storeManager = $storeManager; }//__construct /** * Get an associative array of [store_id => root_category_id] values for all stores * @return array */ public function getAllStoreRootCategories() { $storeroots = []; foreach ($this->storeManager->getStores() as $store) { $storeroots[$store->getId()] = $store->getRootCategoryId(); } return $storeroots; }//getAllStoreRootCategories /** * Get the root category id of a store * @param int|string|\Magento\Store\Model\Store $store The store to get category from, either by store_id, store_code or the \Magento\Store\Model\Store instance itself * @return int root category of store * @throws \Exception if no such store was found */ public function getStoreRootCategoryId($store) { # Get \Magento\Store\Model\Store instance by id if (is_int($store)) { $store = $this->storeManager->getStore($store); } # Get \Magento\Store\Model\Store instance by code if (is_string($store)) { foreach ($this->storeManager->getStores() as $storeModel) { if ($storeModel->getCode() == $store) { $store = $storeModel; break; } } } # Get root category id from \Magento\Store\Model\Store instance if ($store instanceof \Magento\Store\Model\Store) { return $store->getRootCategoryId(); } # If no \Magento\Store\Model\Store instance was supplied or found by id/code throw new \Exception('No such store found: ' . var_export($store, true)); }//getStoreRootCategoryId }//class Store<?php class your class_name { public function __construct( \Magento\Store\Model\StoreManagerInterface $_storeManager ) { $this->_storeManager = $_storeManager; } public function getRootCategoryId() { $store = 1; $rootCatId = $this->_storeManager->getStore($store)->getRootCategoryId(); //$rootCatId = $this->_storeManager->getStore()->getRootCategoryId();//without assign store id } }¡Gracias Arón! Entonces, para que sea muy fácil de entender, si va a usar esto dentro de un módulo, debe usar la inyección directa de la siguiente manera:
<?php namespace ... use ... class Classname { /** @var \Magento\Store\Model\Store */ protected $_store; public function __construct( \Magento\Store\Model\Store $store ) { $this->_store = $store; } public function getRootCategoryId() { return $this->_store->getStoreRootCategoryId(); } }