如何从magento2或magento2.0中的产品id获取产品信息?

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

如何在 magento2 中通过产品 ID 获取所有产品详细信息?我想在主页上显示带有图片的单个产品详细信息。任何帮助将不胜感激。

试试下面的代码。可能对你有帮助。

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

为此,最好在 Magento 2 中使用 Service Layer

protected $_productRepository;

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

public function getProductById($id)
{
    return $this->_productRepository->getById($id);
}
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);
}

如果您不想只获取有关产品的几个属性并希望避免加载产品,则可以使用集合来实现。只需注入 class \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory 像这样:

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

然后像这样创建一个简单的集合:

$productID = 10;
$product = $this->_collection
    ->create()
    ->addAttributeToSelect(['some_attribute'])
    ->addAttributeToFilter('entity_id', $productID)
    ->getFirstItem();
return $product->getSomeAttribute();
<?php 
$productId = 10;
$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();
$currentproduct = $objectManager->create('Magento\Catalog\Model\Product')- 
>load($productId);
?>