当前位置: 首页>>技术解读>>正文


Magento2:如何通过id加载产品

webfans 技术解读 , , 去评论

问题描述

我使用以下代码段在自定义模板中获得了产品集合:

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

 /** @var \Magento\Catalog\Model\ResourceModel\Product\Collection
  $productCollection */
  $productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection');
 /** Apply filters here */

 $productCollection->load();

 foreach ($productCollection as $p)
 {
  echo "<pre>";
  print_R($p->getData());
 }
Here i got array with product id like this

 Array
(
[entity_id] => 1
[attribute_set_id] => 4
[type_id] => virtual
[sku] => Double Corona Natural (box of 25)
[has_options] => 0
[required_options] => 0
[created_at] => 2015-12-23 09:20:38
[updated_at] => 2015-12-23 09:20:38
[is_salable] => 1
)

从这个entity_id,我如何像在Magento 1.x中那样加载产品?

$_product = Mage::getModel('catalog/product')->load($productID);  

最佳解决方案

对象方法

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($product_id);

工厂方法

<?php
namespace Test\Module\Block;

class Product extends \Magento\Framework\View\Element\Template
{

  protected $_productloader;  


  public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Model\ProductFactory $_productloader

    ) {


        $this->_productloader = $_productloader;
        parent::__construct($context);
    }
    public function getLoadProduct($id)
    {
        return $this->_productloader->create()->load($id);
    }

}

phtml文件代码

$product=$this->getLoadProduct(20);
echo $product->getName();

在Magento 2.1

<?php
    namespace Test\Module\Block;
    use Magento\Catalog\Api\ProductRepositoryInterface;
    class Product extends \Magento\Framework\View\Element\Template
     {
          protected $productRepository; 
          protected $_storeManager; 

          public function __construct(
            \Magento\Framework\App\Action\Context $context,
            ProductRepositoryInterface $productRepository
          ) {
              parent::__construct($context);

              $this->productRepository = $productRepository;
          }
          public function getProduct()
          {

              $productId=1;
              return $product = $this->productRepository->getById($productId);
          }
      }

Reference

参考资料

本文由朵颐IT整理自网络, 文章地址: https://duoyit.com/article/2011.html,转载请务必附带本地址声明。