0

I am trying to get customers from the database whose order was cancelled, and I am able to do this via Query. But I think the standard way should be without using Queries. So is there a way I can accomplish this? I searched on google but result is quite ambiguous and mostly for Magento 1.x where as I need for Magento 2.3.

My Query:

SELECT customer_id, count(`entity_id`) as custCount from $tableName WHERE `status` = 'cancel'

Any help here?

0

You need to use the order collection of Magento

$collection = $this->_orderCollectionFactory->create()->getCollection()
            ->addFieldToFilter('status', ['eq' => 'cancel']);

Maybe this link can help you: https://www.mageplaza.com/devdocs/get-all-order-collection-filters-magento-2.html

0

Your can get customers details whose orders are cancelled by this way

 public function __construct(
        \Magento\Sales\Model\OrderFactory $orderFactory,
        \Magento\Customer\Model\CustomerFactory $customerFactory
  ) {
        $this->_customerFactory = $customerFactory;
        $this->orderFactory = $orderFactory;
    }
public function getCustomerCollection() {
        $customerIdArray = array();
        $collection = $this->orderFactory->create()->getCollection()
        ->addFieldToSelect('customer_id')
        ->addFieldToFilter('status', ['eq' => 'cancel']);
        foreach ($collection as $items) {
            array_push($customerIdArray, $items['customer_id']);
        }
        $customerCollection = $this->_customerFactory->create()->getCollection()
        ->addFieldToFilter('entity_id', array('in' => $CustomerIdArray));        
        return $customerCollection;
    }
0

Use magento standard as below using collections

public function __construct(
        \Magento\Sales\Model\OrderFactory $orderFactory,
        \Magento\Customer\Model\CustomerFactory $customerFactory
  ) {
        $this->customerFactory = $customerFactory;
        $this->orderFactory = $orderFactory;
    }
public function execute() {
        $collection = $this->orderFactory->create()->getCollection()
        ->addFieldToSelect('customer_id')
        ->addFieldToFilter('status', ['eq' => 'cancel']);

        var_dump($collection->getSelect());
    }

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.