【问题标题】:Can't filter product collection by type_id无法按 type_id 过滤产品集合
【发布时间】:2013-11-09 06:57:46
【问题描述】:

我正在观察 catalog_product_collection_load_before 事件并尝试根据其 type_id 过滤产品集合。但是,我不断收到 Column not found: 1054 Unknown column 'e.type_id' in 'where clause 错误。

代码是这样的:

$observer->getCollection()->addFieldToFilter(array(
    array(
        'attribute' => 'price',
        'eq'      => '20',
        ),
    array(
        'attribute' => 'type_id',
        'neq'       => 'simple',
        ),
    ));

我什至试着像这样让它变得更简单,但还是不行。

$observer->getCollection()->addFieldToFilter('type_id','simple');

它适用于价格、名称、entity_id 等其他属性,但不适用于 type_id。这是为什么呢?

【问题讨论】:

  • 你找到解决办法了吗?

标签: magento


【解决方案1】:

在集合中尝试这段代码。

$collection->getSelect() ->joinInner(array(’cpe’ => ‘catalog_product_entity’),’e.entity_id = cpe.entity_id’) ->where("cpe.type_id = ‘simple’");

不要使用addAttributeToFilter,因为在这个通过价格过滤时,主表变成了catalog_product_index_price,所以我们可以通过type_id进行过滤,上面的代码对我来说很好。

请试试这个。

【讨论】:

  • 太棒了。这是此问题的唯一有效解决方案。
【解决方案2】:

试试下面的代码,如果它适合你:

$observer = Mage::getModel('catalog/product')->getCollection()
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('type_id', array('eq' => 'simple'))->load();

【讨论】:

  • 我得到了致命错误:达到了“100”的最大函数嵌套级别,正在中止!错误。最后一个堆栈是 Mage_Core_Model_Store->getId( )..\Store.php:673。这甚至不适用于任何其他属性,例如名称、价格。
【解决方案3】:

试试下面的代码,它可以帮助你:

$observer = Mage::getModel('catalog/product')->getCollection()
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('type_id', array('eq' => 'simple'))
    ->addFieldToFilter(
        array(
          array(
           'attribute' => 'price',
           'eq'      => '20',
          )
        )
    )
    ->load();

【讨论】:

  • addAttributeToFilter 和 addFieldToFilter 基本上是相同的方法,因为在 Varien_Data_Collection_Db 中,addFieldToFilter() 映射到 addAttributeToFilter()。当您两次调用这些方法中的任何一个时,您都在进行 AND 操作。我需要 OR 手术。
猜你喜欢
  • 2014-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多