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.
Add a comment
|
2 Answers
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.
-
Thanks for the answer, I think the missing part was the fact that second argument has to be an array.– TimikCommented May 9, 2017 at 16:57
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;
}