如何在Magento Collection中添加OR条件

时间:2012-09-25 09:30:02

标签: magento magento-1.7

我想通过在集合

中应用 OR 条件来从表中获取数据

我正在使用这些代码行

$collect  = Mage::getModel('storelocater/storelocater')->getCollection()->addFieldToFilter(array(
                array(
'attribute' => 'country', 'eq' => 'india'),
array(
'attribute' => 'state', 'eq' => 'up')
)); echo $data = $collect->getSelect();

打印输出


    选择main_table。* FROM storelocater AS main_table WHERE((数组='')或(数组=''))

我还使用了 addAttributeToFilter 而不是 addFieldToFilter ,但它返回了致命错误

4 个答案:

答案 0 :(得分:5)

addAttributeToFilter功能仅适用于EAV实体(如客户,产品,类别等)。 addFieldToFilter OR 运算符的语法略有不同:

$collect  = Mage::getModel('storelocater/storelocater')
    ->getCollection()->addFieldToFilter(array('country','state'), array('india','up'));

答案 1 :(得分:3)

除了Slayer Birden回答。

您还可以创建更复杂的查询,例如

    $rulesCollection
        ->addOrder('sort_order', Zend_Db_Select::SQL_ASC)
        ->addFieldToFilter(
            array('to_date', 'to_date'),
            array(array('gteq' => $now), array('null' => 'null')))
        ->addFieldToFilter(
            array('from_date', 'from_date'),
            array(array('lteq' => $now), array('null' => 'null')))
        ->addFieldToFilter('is_active', '1');

构造了这样的SQL:

     SELECT `main_table`.* FROM `enterprise_targetrule` AS `main_table` 
     WHERE ((to_date >= '2013-03-21') OR (to_date IS NULL)) 
     AND ((from_date <= '2013-03-21') OR (from_date IS NULL)) 
     AND (is_active = '1') 
     ORDER BY sort_order ASC

答案 2 :(得分:2)

$collection->addFieldToFilter(array(
                array('attribute'=>'name', array('like' => '%'.$qry.'%')),
                array('attribute'=>'sku',  array('like' => '%'.$qry.'%'))));
for search by name and search by sku

答案 3 :(得分:0)

有关 $ collections = Mage :: getModel(&#39; sales / order&#39;) - &gt; getCollection()               - &gt; addAttributeToFilter(&#39; increment_id&#39;,array(&#39; in&#39; =&gt; $ sellerIncrementIds))               - &gt; addAttributeToFilter(&#39; status&#39;,[&#39; in&#39; =&gt; [&#39; pending&#39;,&#39; pending_seller_confirmation&#39;]]);