m2根据产品id或者sku获取产品(get product by id or sku)
m2根据产品id或者sku获取产品(get product by id or sku)
一,根据产品id获取产品对象
方式1:用构造函数获取
private $productFactory; public function __construct( MagentoCatalogModelProductFactory $productFactory ) { $this->productFactory = $productFactory; } public function getProductById($id){ $product = $this->productFactory->create(); return $product->load($id); }
方式2: 用对象管理器获取
public function getProductById($id){ $object_manager = MagentoFrameworkAppObjectManager::getInstance(); return $object_manager->get('MagentoCatalogModelProductFactory')->create()->get($id); }
二,根据产品sku获取产品对象
方式1:用构造函数获取
private $productRepository; public function __construct( MagentoCatalogApiProductRepositoryInterface $productRepository ... ) { $this->productRepository = $productRepository; ... } public function getProductBySku($sku){ return $this->productRepository->get($sku); }
方式2: 用对象管理器获取
public function getProductBySku($sku){ $object_manager = MagentoFrameworkAppObjectManager::getInstance(); return $object_manager->get('MagentoCatalogApiProductRepositoryInterface')->get($sku); }
这里用MagentoCatalogModelProductFactory模型获取也可以,首先需要根据sku查到id
public function getProductBySku($sku){ $object_manager = MagentoFrameworkAppObjectManager::getInstance(); $product = $object_manager->get('MagentoCatalogModelProductFactory')->create(); $product->load($product->getIdBySku($sku)); }
根据MagentoCatalogModelProductFactory模型获取是速度最快效率最高的,也是最推荐的。