且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Magento 以任意顺序获取产品集合

更新时间:2023-11-30 09:57:04

集合继承自类

Varien_Data_Collection_Db

该类中有一个名为 addOrder 的方法.

There's a method named addOrder on that class.

public function addOrder($field, $direction = self::SORT_ORDER_DESC)
{
    return $this->_setOrder($field, $direction);
}

所以,你会认为这样的东西应该适用于基本的订购

So, you'd think something like this should work for basic ordering

Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('*')
->addOrder('entity_id');

然而,事实并非如此.由于 EAV 集合中涉及的复杂连接,有一种特殊的方法用于向 order 子句添加属性

However, it doesn't. Because of the complex joining involved in EAV Collections, there's a special method used to add an attribute to the order clause

Mage_Catalog_Model_Resource_Eav_Mysql4_Product_Collection::addAttributeToSort

然而,这只能用于添加简单的属性.要创建任意排序,您需要直接操作 Zend_Select 对象.我不喜欢这个,也不喜欢使用自定义的 mysql 函数来实现,但它似乎是唯一的方法

However again, this can only be used to add simple attributes. To create an arbitrary sort, you'll need to manipulate the Zend_Select object directly. I'm not a big fan of this, and I'm not a big fan of using custom mysql functions to achieve things, but it appears it's the only way to do this

我在股票安装上测试了以下代码并获得了预期的结果.您应该能够使用它来获得您想要的东西.

I tested the following code on a stock install and got the desired results. You should be able to use it to get what you want.

        $ids = array(16,18,17,19);
        $products = Mage::getModel('catalog/product')->getCollection()
        ->addAttributeToSelect('*')
        ->addAttributeToFilter('entity_id',$ids);           

                    //shakes fist at PDO's array parameter
                    $ids = array_map('intval', $ids);
        $products->getSelect()->order("find_in_set(e.entity_id,'".implode(',',$ids)."')");
        foreach($products as $product)
        {
            var_dump($product->getEntityId());
            var_dump($product->getSku());
        }