0

I need to filter order collection based on payment method. I tried the following:

$customerOrderCollection = $this->orderCollectionFactory->create()->addFieldToFilter('customer_id', $customerId)
                                                            ->addFieldToFilter('status', 'pending');
    /* join with payment table */
$customerOrders = $customerOrderCollection->getSelect()
                                              ->join(["sop" => "sales_order_payment"],
                                                      'main_table.entity_id = sop.parent_id',
                                                       array('method')
                                                )
                                              ->where('sop.method = ?',$paymentMethod );

But I am not able to apply getData() method on the above collection. I need to check if at least a single order exists based on above conditions

Is there a way to join collection and also get data?

2 Answers 2

1

You can simply use foreach and if conditions to get the order filter by Payment method.

$customerOrderCollection = $this->orderCollectionFactory->create()->addFieldToFilter('customer_id', 
                           $customerId)->addFieldToFilter('status','pending');
foreach($customerOrderCollection as $customerOrder) {
   if($customerOrder->getPayment()->getMethod() == $paymentMethod) {
    print_r($customerOrder->getData()); //To display data
    //Your actions
   }
}
2
  • I am aware of this method. I want to know if there is any way in Magento 2 to join collection and get data.
    – Toji
    Commented Aug 26, 2020 at 11:38
  • This would be a good method to go for I guess. Because making a join query will slow down the performance compared to the one shared in the answer. Commented Aug 26, 2020 at 13:39
1

I was able to solve this using the following:

$customerOrderCollection = $this->orderCollectionFactory->create()->addFieldToFilter('customer_id', $customerId)
                                                                ->addFieldToFilter('status', 'pending');
/* join with payment table */
$joinQuery = $customerOrderCollection->getSelect()
                                             ->join(["sop" => "sales_order_payment"],
                                                          'main_table.entity_id = sop.parent_id',
                                                           array('method')
                                                   )
                                              ->where('sop.method = ?',$paymentMethod );
$customerOrders = $customerOrderCollection->load($joinQuery)->getData();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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