如何借助 Magento 推荐的一些简单代码从产品 ID 和 SKU 加载产品。
让我们首先看看如何从产品 ID 加载产品。
方法 – 1: Magento 不推荐使用这种简短的方法,因此我们也不使用。
1
2
3
|
$productid = 32;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->get('Magento\Catalog\Api\ProductRepositoryInterface')->getById($productid);
|
方法 - 2:当您需要产品信息时,Magento 强烈推荐使用此方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<?php
namespace Vendor\Extension\Block;
class Product extends \Magento\Framework\View\Element\Template
{
protected $productrepository;
public function __construct(\Magento\Catalog\Api\ProductRepositoryInterface $productrepository) {
$this->productrepository = $productrepository;
}
public function getProductDataUsingId($productid) {
return $this->productrepository->getById($productid);
}
}
PHTML file code,
$product = $block->getProductDataUsingId(32);
echo $product->getName();
|
现在,我们来看看如何按产品SKU加载产品。
方法 – 1: Magento 不推荐使用这种简短的方法,因此我们也不使用。
1
2
3
|
$productsku = "productsku";
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->get('Magento\Catalog\Api\ProductRepositoryInterface')->get($productsku);
|
方法 - 2:当您需要产品信息时,Magento 强烈推荐使用此方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
<?php
namespace Vendor\Extension\Block;
class Product extends \Magento\Framework\View\Element\Template
{
protected $productrepository;
public function __construct(\Magento\Catalog\Api\ProductRepositoryInterface $productrepository) {
$this->productrepository = $productrepository;
}
public function getProductDataUsingSku($productsku) {
return $this->productrepository->get($productsku);
}
}
PHTML file code,
$product = $block->getProductDataUsingSku(“productsku”);
echo $product->getName();
|
所以,现在就这样了。使用这些代码,您将能够按 ID 或 SKU 加载产品信息。