简体   繁体   中英

Magento2 get products collection

I am trying to get store view specific product attribute values for all(actually filtered list but that's irrelevant) products like so:

<?php

/* @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $collectionFactory */
$collection = $collectionFactory->create()->setStoreId(3)->load();

foreach ($collection as $product) {
    var_dump($product->getSku());
    var_dump($product->getName());
}

SKU is returned as expected(as it's general anyway) but product name is not - instead NULL is returned.

It works fine in adminhtml product edit controller where builder is used. The only difference is that edit controller works with Model\\Product model; collection for some reason works with Model\\Product\\Interceptor . Have tried to load each product in the loop using Model\\ProductFactory (which is how it is done in edit controller) - doing so $product->getName() returns corresponding value(however I was not able to get other relevant product attributes). Loading product once again in the loop is wrong off course.

So the question : What is the expected way of retrieving products and getting product attribute(description, weight etc) values for given store view?

<?php

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');

$collection = $productCollection->create()
            ->addAttributeToSelect('*')
            ->load();

foreach ($collection as $product){
    echo 'Name  =  '.$product->getName().'<br>';
}  

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM