2

The following code does not give me any output.

    $collection = Mage::getModel('sales/order_status_history')->getCollection()->getLastItem();
    print_r($collection->getData());

I have SQL Query for this but I have to use magento collection for this.

   SELECT MAX(entity_id) AS entity_id FROM sales_flat_order_status_history

Any idea ?

4 Answers 4

4

Try using an expression. You will have more control over what you're attempting to query.

$collection = Mage::getModel('sales/order_status_history')->getCollection()
    ->addFieldToSelect(new Zend_Db_Expr('MAX(entity_id) AS entity_id'))
    ->getFirstItem()
;

$maxEntityId = $collection->getData('entity_id');
1
  • MAX(entity_id) is much more efficient than setOrder , as it is much less ressource intensive for the database engine. So, even if it seems less beautiful to have some pure SQL bits wrapped by a Zend DB Expr, it will be much better to use daXXon's solution.
    – Cedric
    Nov 14, 2018 at 9:49
1

You can use setOrder('Index','Order') function for getting max data

 $maxData=Mage::getResourceModel('sales/order_status_history_collection')
                  ->setOrder('created_at', 'desc')->getFirstItem()

print_r( $maxData->getData());
1
    $collection = Mage::getModel('sales/order_status_history')->getCollection();
    $collection->getSelect()->order('entity_id DESC');
    $collection->setPageSize(1);
    $maxId = $collection->getFirstItem()->getId();
4
  • Who marked my post for deletion - please leave your feedback
    – zhartaunik
    Aug 3, 2015 at 13:54
  • 1
    This will load the ENTIRE sales/order_status_history table and then get the first item of the underlying Varien_Collection. Add ->setPageSize(1) to the collection to LIMIT the query.
    – Elias
    May 3, 2017 at 12:01
  • Good stuff!....
    – zhartaunik
    May 4, 2017 at 7:19
  • While this works, ordering is much more resource consuming for a database than the SQL MAX function itself
    – Cedric
    Nov 14, 2018 at 9:36
0
$collection->addExpressionFieldToSelect("max_id", "MAX(entity_id)", [])
->getFirstItem()
->getData("max_id");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.