How to get product information from product id in magento2 or magento2.0?

≡放荡痞女 提交于 2019-12-11 10:08:57

问题


How to get all product details by product id in magento2? I want to display a single product detail with the image on the homepage. Any help would be appreciated.


回答1:


For this purpose, it's better to use Service Layer in Magento 2.

protected $_productRepository;

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

public function getProductById($id)
{
    return $this->_productRepository->getById($id);
}



回答2:


Try below code. It may help you.

<?php 
   $productId = 10;
   $objectManager =  \Magento\Framework\App\ObjectManager::getInstance();
   $currentproduct = $objectManager->create('Magento\Catalog\Model\Product')->load($productId);
?>



回答3:


use Magento\Catalog\Model\ProductFactory;
/**
 * @var ProductFactory
 */
protected $_modelProductFactory;
public function __construct(
    ...      
    ProductFactory $modelProductFactory,  
    ...
)
{           
    $this->_modelProductFactory = $modelProductFactory; 
    ...
}

public function getProductInformation($productId)
{
    return $this->_modelProductFactory->create()->load($productId);
}



回答4:


If you wan't to get just a couple of attributes about the product and want to avoid loading the product, you can do that using a collection. Just inject the class \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory like so:

public function __construct(
    Context = $context,
    //...
    \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $collectionFactory,
    //...
    array $data = []
) {
    $this->_collection = $collectionFactory();
    parent::__construct($context, $data);   
}

and then create a simple collection like this:

$productID = 10;
$product = $this->_collection
    ->create()
    ->addAttributeToSelect(['some_attribute'])
    ->addAttributeToFilter('entity_id', $productID)
    ->getFirstItem();
return $product->getSomeAttribute();



回答5:


<?php 
$productId = 10;
$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();
$currentproduct = $objectManager->create('Magento\Catalog\Model\Product')- 
>load($productId);
?>


来源:https://stackoverflow.com/questions/34894534/how-to-get-product-information-from-product-id-in-magento2-or-magento2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!