Magento – Magento 2 get catalog rule for current product

catalog-rulesmagento2productproduct-page

I would like to get the current catalog rule for the product on the product page. I want to be able to output the name on the page.

I know this is possible in magento 1 but cannot find any function in code for magento 2.

Best Answer

This table catalogrule_product holds all the catalog rules applied to a particular product with the discount amount.

You could use this resource model Magento\CatalogRule\Model\ResourceModel\Rule::getRulesFromProduct($date, $websiteId, $customerGroupId, $productId) to get rules applied to a product.

<?php
namespace Vendor\Module\Model;

class Sample extends \Magento\Framework\Model\AbstractModel
{
    ...

    /**
     * @var \Magento\CatalogRule\Model\ResourceModel\Rule
     */
    protected $ruleResource;

    ...

    public function __construct(
        ...
        \Magento\CatalogRule\Model\ResourceModel\Rule $rule
    ) {
        ...
        $this->ruleResource = $rule;
        ...
    }

    ...

    /**
     * @param int|string $date
     * @param int $websiteId
     * @param int $customerGroupId
     * @param int $productId
     */
    public function getRules($date, $websiteId, $customerGroupId, $productId)
    {
        ...
        /** @var [] $rules catalog rules */
        $rules = $this->ruleResource->getRulesFromProduct($date, $websiteId, $customerGroupId, $productId);
        ...
    }

    ...
}
Related Topic