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

问题描述 投票:1回答:5

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

magento magento2 magento-2.0
5个回答
2
投票

为此,最好在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);
}

0
投票

试试下面的代码。它可能会帮助你。

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

0
投票
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);
}

0
投票

如果您不想获得有关产品的几个属性并希望避免加载产品,则可以使用集合来实现。只需像这样注入类\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();

0
投票
<?php 
$productId = 10;
$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();
$currentproduct = $objectManager->create('Magento\Catalog\Model\Product')- 
>load($productId);
?>
© www.soinside.com 2019 - 2024. All rights reserved.