Magento 2 – Load Product Specifying Store

magento2productstore-view

I have a multi store view with different languages ​​to describe the product. Each store has a different locale defined.

I have this code

    $shops = $this->_storeManager->getStores();

    $store_locales = array();
    foreach ($shops as $shop){

        $store_locales[$shop->getName()] = array();
        $store_locales[$shop->getName()][] = $shop->getId();
        $store_locales[$shop->getName()][] = $this->_scopeconfig->getValue('general/locale/code', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $shop->getId());

    }

and now i need to load a product desciption specifying a store id.

Any idea?

Best Answer

Complete untested (sorry!). But as long as you have the product ID you should be able to use the getAttributeRawValue function on the resource model.

class YourClass {
   protected $product;

   public function __construct(
       \Magento\Catalog\Model\Product $product
   ) {
       $this->product = $product;
   }

   public function getDescription($productId, $store)
   {
       return $this->product->getResource()->getAttributeRawValue($productId, 'description', $store);
   }
}

If you're happy to load the full product model then do the following instead.

class YourClass {
    protected $productRepository;

    public function __construct(
        \Magento\Catalog\Model\ProductRepository $productRepository
    ) {
        $this->productRepository = $productRepository;
    }

    public function getProduct($id, $storeId) {
        return $this->productRepository->getById($id, false, $storeId);
    }
}
Related Topic