sort Magento collection AFTER load

后端 未结 5 1154
无人及你
无人及你 2020-12-09 07:02

The Magento collection sorting functions (e.g. Mage_Eav_Model_Entity_Collection_Abstract::addAttributeToSort) work by adding an ORDER BY clause to

5条回答
  •  执念已碎
    2020-12-09 07:36

    There is no proper way of doing it. But I think it is possible with using of Reflection. You can retrieve $_items property of collection object, sort them and set it back to the collection.

    function sortCollection(Varien_Data_Collection $collection, callable $sorter) {
        $collectionReflection = new ReflectionObject($collection);
        $itemsPropertyReflection = $collectionReflection->getProperty('_items');
        $itemsPropertyReflection->setAccessible(true); // Make it accessible
    
        $collectionItems = $itemsPropertyReflection->getValue($collection);
    
        usort($collectionItems, $sorter);
    
        $itemsPropertyReflection->setValue($collection, $collectionItems);
    
        $itemsPropertyReflection->setAccessible(false); // Return restriction back
    
        return $collection;
    }
    

提交回复
热议问题