7 magento
是否可以使用id的数组过滤Magento集合但是按照传递给过滤器的id的顺序排序集合结果.
例如:
$collection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToFilter('entity_id', array(
'in' => array(1, 3, 2),
));
Run Code Online (Sandbox Code Playgroud)
我希望这个系列产品按顺序排列,1,3,2这样当循环收集它们时,它们会按特定顺序出现?
我目前唯一的选择是手动创建一系列产品:
$productIds = array(1,3,2);
$collection = array();
foreach($productIds as $productId) {
$collection[] = Mage::getModel('catalog/product')->load($productId);
}
Run Code Online (Sandbox Code Playgroud)
这显然有效但似乎是一种丑陋的方式来做到这一点.
有没有办法纯粹通过magento集合来做到这一点?
Dre*_*ter 12
$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))
Run Code Online (Sandbox Code Playgroud)
这是一个具有挑战性的问题,这是一个应该有效的解决方案:
$collection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToFilter('entity_id', array(
'in' => array(1928, 1930, 1929),
))
->addAttributeToSort('entity_id = 1928', 'ASC')
->addAttributeToSort('entity_id = 1930', 'ASC')
->addAttributeToSort('entity_id = 1929', 'ASC')
;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
12604 次 |
最近记录: |