浏览文章

文章信息

Magento2 【后端】rest接口 获取可配置产品配置项 以及配置项库存 价格范围等 12971

具体类自己找

function getDetail(string $sku): \Magento\Catalog\Api\Data\ProductInterface
    {
        $storeId = $this->storeManager->getStore()->getId();
        $this->appEmulation->startEnvironmentEmulation($storeId, \Magento\Framework\App\Area::AREA_FRONTEND, true);
        /**@var $repository \Magento\Catalog\Model\ProductRepository */
        $repository = $this->productRepositoryFactory->create();
        /**@var $product \Magento\Catalog\Api\Data\ProductInterface */
        $product = $repository->get($sku, true, $storeId);
        /**@var $imageHelper \Magento\Catalog\Helper\Image */
        $imageHelper = $this->imageHelperFactory->create();
        $product->setData('image', $imageHelper
            ->init($product, 'product_page_image_small')
            ->resize($this->imageH, $this->imageW)
            ->getUrl());
        $product->setData('small_image', $imageHelper
            ->init($product, 'product_small_image')
            ->resize($this->imageH, $this->imageW)
            ->getUrl());
        $product->setData('thumbnail', $imageHelper
            ->init($product, 'product_thumbnail_image')
            ->resize($this->imageH, $this->imageW)
            ->getUrl());
        if ($product->getTypeId() == 'configurable') {
            $data = $product->getTypeInstance()->getConfigurableOptions($product);
            foreach ($data as &$attr) {
                foreach ($attr as &$p) {
                    $pd = $repository->get($p['sku']);
                    $p['price'] = $pd->getPrice();
                    $p['stock'] = $pd->getExtensionAttributes()->getStockItem()->getData('qty');
                }
            }
            $regularPrice = $product->getPriceInfo()->getPrice('regular_price');
            $product->setData('options', [[
                    'regular_price' => [
                        'miniPrice' => $regularPrice->getMinRegularAmount()->getValue(),
                        'maxPrice' => $regularPrice->getMaxRegularAmount()->getValue(),
                    ],
                    'opt' => $data,
                ]
                ]
            );
        }
        // 仿真环境 结束
        $this->appEmulation->stopEnvironmentEmulation();
        return $product;
    }

以上使用了仿真环境,不想用的去掉就可以了,但是图片会找不到。


原创