1

I have got order collection with the following code:

$orders = $objectManager->create('Magento\Sales\Model\Order')->getCollection();

Which is working fine. Problem is that it returns all types of orders including 'processing', 'cancelled' etc. I don't want the cancelled order in this collection.

I don't know how to exclude cancelled order in the above code.

Hope somebody helps.

0

2 Answers 2

4

Try this,

$orders = $objectManager->create('Magento\Sales\Model\Order')->getCollection();
$orders->addFieldToSelect('*')->addFieldToFilter('status', array('in' => array(complete,processing)));

Status not in cancelled order will get into the collection.

am not sure about the status name cancelled make sure you use the exact one in the table sales_order table.

8
  • Call to undefined method Magento\Sales\Model\ResourceModel\Order\Collection::addFieldToField() Apr 4, 2019 at 13:05
  • sorry typo erro check now Apr 4, 2019 at 13:06
  • I have checked it in db for status, its 'canceled' but still it is not working niether yours nor mine. Apr 5, 2019 at 10:42
  • Will it returns collection Apr 5, 2019 at 10:44
  • It is returning collection including all types of status Apr 5, 2019 at 10:45
3

It isn't the best way to get collections in M2 using object manager. Use collection factorty for this purpose instead. Here's a short example:

use Magento\Sales\Model\ResourceModel\Order\CollectionFactory;

class SomeClass
{
    ...
    public function __construct(
        ...
        CollectionFactory $orderCollectionFactory
        ...
    ) {
        ...
        $this->collectionFactory = $orderCollectionFactory;
        ...
    }
    ...
     public function getOrders(){
         $orders = $this->collectionFactory()->create()
             ->addFieldToSelect('*')
             ->addFieldToFilter('status', ['neq' => 'cancelled']);
         return $orders;
    }
}
1
  • Magento is spelled using broken English (i.e. American). "Correct" spelling for the filter is "canceled" (even though the actual correct spelling is "cancelled", GARGH!!!) Jun 29, 2020 at 13:21

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.