【问题标题】:Multiple fields to sort a magento collection多个字段对 magento 集合进行排序
【发布时间】:2015-10-01 05:48:24
【问题描述】:

这里是目标sql查询: ...... order by field1 asc, price_index.min_price desc

这是我的代码

$productCollection->getCollection()
         ->setOrder('field1', 'asc')
         ->setOrder('price', 'desc')

但在我的结果中,价格始终是第一排序字段。任何人都可以帮助我吗?非常感谢你

【问题讨论】:

    标签: php magento magento-1.8 magento-1.9


    【解决方案1】:
    $collection->getSelect()
        ->order('field1 asc');
    

    或按多个排序:

     $collection->getSelect()
        ->order(array('field1 asc', 'price desc'));
    

    【讨论】:

      【解决方案2】:

      要使用多个字段进行排序,您可以将调用链接到 Collection 的方法 addAttributeToSort()

      $productCollection->getCollection()
               ->addAttributeToSort('field1', 'asc')
               ->addAttributeToSort('price', 'desc');
      

      【讨论】:

      • 感谢您的回答。我在获取收集功能中尝试此操作,但这无法正常工作。因为价格将在结果中首次提交。你对我有其他建议吗?谢谢
      【解决方案3】:

      在自定义资源集合上,使用addOrder:

      Mage::getModel('module/model')->getCollection()
          ->addOrder('first', 'ASC')
          ->addOrder('second', 'DESC')
          ->addOrder('other', 'DESC');
      

      【讨论】:

        【解决方案4】:

        使用:

        productCollection->getSelect()->reset(Zend_Db_Select::ORDER); 
        

        然后:

        productCollection->getSelect()
                    ->order(.......) 
        

        该代码将解决此问题^ ^

        【讨论】:

          【解决方案5】:

          要对多个字段进行排序,您可以使用

          $collection = Mage::getModel(‘module/model_name’)->getCollection()
          ->addAttributeToSort(‘order’, ‘ASC’)
          ->addAttributeToSort(‘last_name’, ‘ASC’)
          ->addAttributeToSort(‘first_name’, ‘ASC’);
          

          【讨论】:

          • 感谢您的回答。您的代码在正常字段中正确。但价格我必须从集合中重置订单并再次添加订单:productCollection->getSelect() ->reset(Zend_Db_Select::ORDER) ->order('filed1'') ->order('field2');
          猜你喜欢
          • 2013-09-10
          • 1970-01-01
          • 2013-01-15
          • 1970-01-01
          • 2016-09-12
          • 1970-01-01
          • 1970-01-01
          • 2015-01-26
          相关资源
          最近更新 更多