gpt4 book ai didi

Magento:如何在观察者内部合并两个集合?

转载 作者:行者123 更新时间:2023-12-04 05:31:02 25 4
gpt4 key购买 nike

我需要重新组织产品列表类别页面。
我的产品中有一个 date_field 属性需要遵循此排名:

  • date_field >= today 的产品最先出现
  • 将它合并到 date_field < today
  • 的产品

    因此,我使用以下代码为 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/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com