Magento:组合eq并在addAttributeToFilter中为null

tim*_*hka 6 magento

我想结合OR"is null"和"eq"=> array()

$collection->addAttributeToFilter('attributename', array('is' => null));
$collection->addAttributeToFilter('attributename', array(115,116));
Run Code Online (Sandbox Code Playgroud)

但这不起作用.

Jür*_*len 12

要使用addAttributeToFilter()OR条件你可以通过这样的一个数组的数组:

$collection->addAttributeToFilter(
    array(
        array(
            'attribute' => 'name_of_attribute_1',
            'null' => 'this_value_doesnt_matter'
        ),
        array(
            'attribute' => 'name_of_attribute_2',
            'in' => array(115, 116)
        )
    )
);
Run Code Online (Sandbox Code Playgroud)

NULL关键字进行过滤的定义乍一看可能看起来有点令人困惑,但是一旦你习惯它就很简单.

Magento的支持两种类型的过滤器类型的string,即'null''notnull',针对comparisions NULL关键字.

要知道,即使你需要传递键=>值对(因为关联数组时),该值将总是被忽略,当过滤器类型'null''notnull'使用.

var_dump(
    Mage::getModel('catalog/product')
    ->getCollection()
    ->addFieldToFilter(
        array(
            array(
                'attribute' => 'description',
                'null' => 'this_value_doesnt_matter'
            ),
            array(
                'attribute' => 'sku',
                'in' => array(115, 116)
            )
         )
     )
     ->getSelectSql(true)
 );
Run Code Online (Sandbox Code Playgroud)

转储的输出可能会因您的商店配置(属性ID,商店数量等)而异,但子句中的OR逻辑WHERE应始终保持不变:

SELECT 
    `e`.*,
    IFNULL(_table_description.value, _table_description_default.value) AS `description`
FROM
    `catalog_product_entity` AS `e`
INNER JOIN
    `catalog_product_entity_text` AS `_table_description_default` ON
    (_table_description_default.entity_id = e.entity_id) AND
    (_table_description_default.attribute_id='57') AND
    _table_description_default.store_id=0
LEFT JOIN
    `catalog_product_entity_text` AS `_table_description` ON
    (_table_description.entity_id = e.entity_id) AND
    (_table_description.attribute_id='57') AND
    (_table_description.store_id='1')
WHERE (
    (IFNULL(_table_description.value, _table_description_default.value) is NULL) OR
    (e.sku in (115, 116))
)
Run Code Online (Sandbox Code Playgroud)

  • 你使用什么类型的收藏?有些像扁平的销售表一样,有自己版本的`addAttributeToFilter`方法,因为它们实际上不是EAV集合.这可能解释了你所看到的差异. (3认同)