I want to fetch all products in my ecommerce and all its attributes. How can I do that? For example, I want to be able to call a function that gets all products, an then one by one fetch all the attributes of that product.
1 Answer
You can try below code for your requirement.
<?php
namespace Test\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{
protected $_productCollectionFactory;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
array $data = []
)
{
$this->_productCollectionFactory = $productCollectionFactory;
parent::__construct($context, $data);
}
public function getProductCollection()
{
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*');
return $collection;
}
}
?>
Display in phtml using block method
$productCollection = $block->getProductCollection();
foreach ($productCollection as $product) {
print_r($product->getData());
echo "<br>";
}
-
What if I want to fetch also all attributes that are not in the default attribute set? Will this work too?– diracCommented Jan 28, 2019 at 14:35
-