我需要重新组织产品列表类别页面。 我的产品中有一个 date_field 属性,需要遵循以下排名:
- 带有 date_field>= 今天的产品首先出现
- 将其合并到具有日期字段 <今天 的产品
因此,我使用以下代码为 catalog_block_product_list_collection 调度程序创建了一个观察者:
$original_collection = clone $observer->getEvent()->getCollection();
$observer->getEvent()->getCollection()
->addAttributeToFilter('data_inicio', array('gteq' => date('Y-m-d')));
$collection2 = $original_collection
->addAttributeToFilter('data_inicio', array('lt' => date('Y-m-d')));
//and after I will merge both collections by adding each item from $collection2 into $observer
但是当在 $collection2 上再次应用相同的过滤器时,会引发以下错误:
You cannot define a correlation name '_table_data_inicio_default' more than once
只有过滤器的第一部分工作正常。 有更好的方法吗?
最佳答案
PHP 克隆的问题是它不是一个深层克隆,因此某些资源是共享的,因此您会看到冲突的名称。我发现最佳实践是在 SQL 中做尽可能多的工作,这样这些小问题就很少出现。
$collection = $observer->getEvent()->getCollection();
// store old ordering
$orderBys = $collection->getSelect()->getPart(Zend_Db_Select::ORDER)
$collection->getSelect()->reset(Zend_Db_Select::ORDER);
// set first order part
$collection->addExpressionAttributeToSelect(
'future',
'IF({{data_inicio}}>="' . date('Y-m-d') . '",1,0)',
'data_inicio')
->addAttributeToSort('future', 'desc');
// reinstate old ordering afterwards
foreach ($orderBys as $orderBy) {
$collection->getSelect()
->order(is_array($orderBy) ? implode(' ', $orderBy) : $orderBy);
}
这里,创建一个表达式 future
来比较日期,然后首先与今天或更大的行进行排序。它不是按 data_inicio
排序的。它可能会覆盖任何默认排序,并且 - 我尚未对此进行测试 - 可能会在用户排序后应用。
关于Magento:如何在观察者内部合并两个集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12628450/