Magento ordering collections after adding items

雨燕双飞 提交于 2019-12-12 03:14:44

问题


i have this method on which i retrieve first a Varien_Data_Collection and then I add items one by one from another Varien_Data_Collection by addItem():

    protected function _prepareCollection(){

    $productId = $this->getRequest()->getParam('id');
    $websiteId = 0;
    if ($store = $this->getRequest()->getParam('store')) {
        $websiteId = Mage::app()->getStore($store)->getWebsiteId();

        $collection = Mage::getModel('productalert/stock')
                ->getCustomerCollection()
                ->join($productId, $websiteId); 

        foreach ($collection as $item) {
            $item->setData('is_customer', 'Sì');
        }


        $guestCollection = Mage::getModel('productsalert/gueststock')->getCollection()
                ->addFieldToFilter("product_id", $productId)
                ->addFieldToFilter("website_id", $websiteId);


        foreach ($guestCollection as $guestItem) {
            $obj = new Mage_Customer_Model_Customer();
            $obj->setData($guestItem->getData());
            $obj->setData('alert_stock_id', ($guestItem->getData('alert_stock_id')+100000000));
            $obj->setData('email', $guestItem->getData('guest_email'));
            $obj->setData('is_customer', 'No');
            $collection->addItem($obj);
        }
        $collection = $collection->setOrder('add_date','ASC');
        $this->_sortCollectionDescByDate($collection);
        $this->setCollection($collection);
    }
    else{
        $this->setCollection(new Varien_Data_Collection());
    }




    return parent::_prepareCollection();

}   

So when i have the final collection i want to set the order since items in it have one attribute in common ('add_date'), so i set the setOrder methos, but it doesn't work (soemone on IRC told me that setOrder modify the query). so I can do it manually but it seems strange to me that there's not to order a collection after adding items. i took a look on Varien_Data_Collection API but I don't see anything that could help me. I've also tried to change the collection class to Varien_Data_Collection_Db and setting the addOrder() method but nothing has changed.

any idea?

thanks!

Luke


回答1:


You can call

$collection->clear();
$collection->....//here you add some logic for ordering;
$collection->load();//here collection with new filters will be loaded. 

OR

You can have some kind of sorting function like specified here in the last message.



来源:https://stackoverflow.com/questions/8355370/magento-ordering-collections-after-adding-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!