Magento-按数组保留顺序收集筛选器 [英] Magento - Collection Filter by Array Keep Order

查看:46
本文介绍了Magento-按数组保留顺序收集筛选器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用ID的数组 BUT 过滤Magento集合,使收集结果按ID传递到过滤器的顺序排序.

Is it possible to filter a Magento collection using an array of id's BUT have the collection results ordered by the order of the id's passed to the filter.

例如:

$collection = Mage::getModel('catalog/product')
                  ->getCollection()
                  ->addAttributeToFilter('entity_id', array(
                       'in' => array(1, 3, 2),
                   ));

我希望该集合按顺序排列产品1,3,2,以便在循环浏览这些集合时,它们按该特定顺序出现?

I would like the collection to have products in order, 1,3,2 so as when looping through the collection they come out in that specific order?

我目前唯一的选择是手动创建一系列产品:

The only alternative i currently have is to manually create an array of products:

$productIds = array(1,3,2);
$collection = array();

foreach($productIds as $productId) {
    $collection[] = Mage::getModel('catalog/product')->load($productId);
}

这显然是可行的,但似乎是一种丑陋的方式.

This obviously works but seems like an ugly way to do this.

有没有一种方法可以纯粹通过magento集合来做到这一点?

is there a way to do this purely via magento collections?

推荐答案

$productIds = array(1,3,2);

/**
 * Build up a case statement to ensure the order of ids is preserved
 */
$orderString = array('CASE e.entity_id');
foreach($productIds as $i => $productId) {
    $orderString[] = 'WHEN '.$productId.' THEN '.$i;
}
$orderString[] = 'END';
$orderString = implode(' ', $orderString);

/**
 * Filter the collection
 */
$productCollection = Mage::getModel('catalog/product')->getCollection()
    ->addAttributeToFilter('entity_id', array('in' => $productIds));

/**
 * Apply the order based on the case statement
 */
$productCollection->getSelect()
    ->order(new Zend_Db_Expr($orderString))

这篇关于Magento-按数组保留顺序收集筛选器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆