Filtering orders by status containing space
-
22-10-2019 - |
Question
I am building a php script for a magento site. The script is located in a subfolder to the document root and is called from cron/terminal. In this script I am trying to create a collection of orders filtered by order status. This is the code I'm using atm:
$orderStatuses = explode(",", $argv[4]);
$rightNow = date("Y-m-d H:i:s");
$midnightToday = date("Y-m-d H:i:s", strtotime('midnight'));
$salesToday = Mage::getModel('sales/order')
->getCollection()
->addFieldToFilter('status', array('in' => $orderStatuses))
->addAttributeToFilter('created_at', array('from' => $midnightToday,'to' => $rightNow))
->addAttributeToSelect('grand_total');
the following parameter is sent to $argv[4]
: 'Processing,Payment Accepted,Complete'
Orders with the status Payment Accepted
are not included in the collection. I have tried to escape the white space in the parameter using \
but the result remain the same. How can I modify my code to include statuses containing white space?
Solution
I think you have to tweak your query a bit. You might want to see the performance hit on this.
First replace your input parameter's space with '%'.
$orderStatuses = preg_replace ( '/[^a-zA-Z\,]/i', '%', $argv[4]);
$orderStatuses = explode(',', $orderStatuses);
Then your Payment Accepted
will be Payment%Accepted
. Now tweak your query.
$salesToday = Mage::getModel('sales/order')
->getCollection()
->addAttributeToFilter('created_at', array('from' => $midnightToday,'to' => $rightNow))
->addAttributeToSelect('grand_total');
foreach ($orderStatus as $_status) {
$salesToday->getSelect()->orWhere('status LIKE ?', "%$_status%");
}
I think this should work.