1

I would like to get a list of orders which have been made by a specific payment method using the search criteria. Is there any way we can achieve this?

The only thing I've found is this thread: Magento 2: Get orders by payment method, which doesn't use searchCriteria. I would like to understand how to do this type of search/join between tables and models in magento 2.

Thanks

1 Answer 1

5

add a new extension attribute to the order:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Api/etc/extension_attributes.xsd">
    <extension_attributes for="Magento\Sales\Api\Data\OrderInterface">
        <attribute code="payment_method" type="string" >
            <join reference_table="sales_order_payment" reference_field="parent_id" join_on_field="entity_id">
                <field>method</field>
            </join>
        </attribute>
    </extension_attributes>
</config>

then use OrderRepository as per your requirement:

$filter = $this->filterBuilder->setField('extension_attribute_payment_method.method')
            ->setConditionType('eq')
            ->setValue($methodCode)
            ->create();

        $searchCriteria = $this->searchCriteriaBuilder
            ->addFilters([$filter])
            ->create();

        $orderList = $this->orderRepository->getList($searchCriteria);

        $numberOrders = $orderList->getTotalCount();
        $result = $orderList->getItems();
4
  • Thanks, it worked like a charm :)
    – PauGNU
    Jun 2, 2020 at 5:40
  • thanks for the feedback, great question that was as It makes me getting on with repository and extension attributes a bit more.. Jun 2, 2020 at 5:41
  • wonderful. but what was the reason to create extension attribute for this. I mean can not we create joins directly in SearchCriteria?
    – sudo55
    Dec 18, 2020 at 7:33
  • The payment method data is not part of the order repository data. This solution exposes this data via an extension attribute. I did find this to be a simple way to add this data. Joins may work too but you’d have likely more hands on code to add I imagine Dec 18, 2020 at 19:13

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.