1

Magento 2 has order status history inside each order which essentially is just comments related to a order. All of them are stored in one single database table sales_order_status_history. Each comment relates to order by value in column parent_id which maps to order_id. I have a set of order id's in an array.
My end goal is to get an array or a collection with comments related to those orders with single query to make it more efficient. I don't want to write direct database queries. I want to utilize collections functionality that I believe allows you to do something like that.

2 Answers 2

3

Assuming $ids is an array, the collection would need to be filtered like this:

$collection->addFieldToFilter('parent_id', array('in' => $ids));

This will allow you to filter by an array.

1
  • Thanks for the answer, I think the missing part was the fact that second argument has to be an array.
    – Timik
    May 9, 2017 at 16:57
1

I assume you are trying to add a method into a class that should retrieve the comment collection.
You need to add this to your class :

protected $historyCollectionFactory;
public function __construct(
    ....
    \Magento\Sales\Model\ResourceModel\Order\Status\History\CollectionFactory $historyCollectionFactory,
    ....
)
{
    ....
    $this->historyCollectionFactory = $historyCollectionFactory;
    ....
}

Then create the method that retrieves the items:

public function getStatusHistoryItems($ids)
{
    $collection = $this->historyCollectionFactory->create();
    $collection->addFieldToFilter('parent_id', $ids);
    //additional collection changes here, if needed.
    return $collection;
}

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.