1

How to get salesrule id from order id,for example:

public function getSalesruleIdByOrderId($orderId){
   //???
}
2

Try this:

$order->getData('applied_rule_ids');

In this field stored all sales rules ids.

You can obtain the order object by id using the Magento\Sales\Api\OrderRepositoryInterface::get($id) method.

Complete class:

<?php
/**
 * Copyright © MageWorx. All rights reserved.
 * See LICENSE.txt for license details.
 */

namespace MageWorx\StackExchange\Model;


use Magento\Framework\Exception\NoSuchEntityException;

class ObtainSalesRulesByOrderId
{
    /**
     * @var \Magento\Sales\Api\OrderRepositoryInterface
     */
    private $orderRepository;

    /**
     * ObtainSalesRulesByOrderId constructor.
     *
     * @param \Magento\Sales\Api\OrderRepositoryInterface $orderRepository
     */
    public function __construct(
        \Magento\Sales\Api\OrderRepositoryInterface $orderRepository
    ) {
        $this->orderRepository = $orderRepository;
    }

    /**
     * @param $id
     * @param bool $asArray
     * @return array|string|null
     */
    public function getSalesRulesByOrderId($id, $asArray = false)
    {
        try {
            /** @var \Magento\Sales\Api\Data\OrderInterface $order */
            $order = $this->orderRepository->get($id);
            $salesRulesIds = $order->getAppliedRuleIds();
            if ($asArray) {
                $salesRulesIds = explode(',', $salesRulesIds);
            }
        } catch (NoSuchEntityException $exception) {
            return null;
        }

        return $salesRulesIds;
    }
}
0

Try to use this below code :

protected $_order;

public function __construct(
    .....
    \Magento\Sales\Module\OrderFactory $order
    .....
)
{
    .....
    $this->_order = $order;
    .....
}

public function yourFunction()
{
    $order_id = 19050;
    $order = $this->_order->create()->load($order_id);
    foreach(explode(",",$order->getAppliedRuleIds()) as $ruleId){
        echo $ruleId."<br/>";
    }   
}
  • the result not in array so i can't loop it – blue Jan 10 at 5:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.