Magento 2 – Get Tier Price by Custom Group

catalogmagento2tierprice

I have set tier price for each custom group for a product. How to do I fetch the tier price by passing customer group id to the product repository. I am using custom REST API

Below is the code sample, I have tried

$productRepo=$this->_productRepository->getById($p,false,$storeIdFromRequest);
$productRepo->getTierPrice();

But this gives always gives me NOT LOGGED IN Customer group price.

{"2":{"price_id":"6","website_id":"0","all_groups":"0","cust_group":"0","price":"125.0000","price_qty":"1.0000","website_price":"125.0000"}}

How do I get tier price by setting customer group in the above code.

Any help would be appreciated

Best Answer

Try this way:


public function __construct(
    \Magento\Catalog\Model\Product\TierPriceManagement $tierPriceManagement
) {
    $this->tierPriceManagement = $tierPriceManagement;
}

After that:


$tierPrices = $this->tierPriceManagement->getList('24-MB01', 0);
foreach ($tierPrices as $tierPrice) {
    print_r($tierPrice->getData());
}

[Update]

For only price, try following way:


public function __construct(
    \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
    \Magento\Catalog\Api\Data\ProductTierPriceInterfaceFactory $priceFactory,
    \Magento\Framework\App\Config\ScopeConfigInterface $config,
    \Magento\Customer\Api\GroupManagementInterface $groupManagement
) {
    $this->productRepository = $productRepository;
    $this->priceFactory = $priceFactory;
    $this->config = $config;
    $this->groupManagement = $groupManagement;

}

And then:


$sku = '24-MB01';
$customerGroupId = 1;
$product = $this->productRepository->get($sku, ['edit_mode' => true]);

$priceKey = 'website_price';
$value = $this->config->getValue('catalog/price/scope', \Magento\Store\Model\ScopeInterface::SCOPE_WEBSITE);
if ($value == 0) {
    $priceKey = 'price';
}

$cgi = ($customerGroupId === 'all'
    ? $this->groupManagement->getAllCustomersGroup()->getId()
    : $customerGroupId);

$prices = [];
foreach ($product->getData('tier_price') as $price) {
    if ((is_numeric($customerGroupId) && intval($price['cust_group']) === intval($customerGroupId))
        || ($customerGroupId === 'all' && $price['all_groups'])
    ) {
        /** @var \Magento\Catalog\Api\Data\ProductTierPriceInterface $tierPrice */
        $tierPrice = $this->priceFactory->create();
        $tierPrice->setValue($price[$priceKey])
            ->setQty($price['price_qty'])
            ->setCustomerGroupId($cgi);
        $prices[] = $tierPrice->getValue();
    }
}
echo '<pre>';print_r($prices);