代码之家  ›  专栏  ›  技术社区  ›  Castro Roy

Magento使用collections创建一个(或)

  •  3
  • Castro Roy  · 技术社区  · 14 年前

    Mage::getModel('comunity/news')->getCollection()
                ->addFieldToFilter('title', array('like'=>'%'.$this->getRequest()->getParam('q').'%'));
    

    有了这个就足够了,而且工作得很完美,但是我需要添加另一个字段,如果你这样做很简单

    Mage::getModel('comunity/news')->getCollection()
                ->addFieldToFilter('title', array('like'=>'%'.$this->getRequest()->getParam('q').'%'))  
               ->addFieldToFilter('shortdesc', array('like'=>'%'.$this->getRequest()->getParam('q').'%'));
    

            if (is_array($fieldName)) {
            foreach ($fieldName as $f) {
                $orSql = array();
                foreach ($condition as $orCondition) {
                    $orSql[] = '('.$this->_getConditionSql($f[0], $f[1]).')';
                }
                $sql = '('. join(' or ', $orSql) .')';
            }
            return $sql;
        }
    

    这里可以做一个(或),我试过了

    ->addFieldToFilter(array (
                    array('field'=>'title', 'like'=>'%'.$this->getRequest()->getParam('q').'%'),
                    array('field'=>'shortdesc', 'like'=>'%'.$this->getRequest()->getParam('q').'%'),
                ))
    

    SELECT `main_table`.* FROM `uhma_comunidad_articulos` AS `main_table` WHERE (())
    

    我需要帮助 谢谢

    3 回复  |  直到 14 年前
        1
  •  1
  •   Jonathan Day    14 年前

    我认为问题是你需要 addAttributeToFilter addFieldToFilter . 拜访 Mage_Catalog_Model_Resource_Eav_Mysql4_Product_Collection 你会看到 方法正在测试数组,然后作为 OR :

    if (is_array($attribute)) {
           $sqlArr = array();
           foreach ($attribute as $condition) {
               $sqlArr[] = $this->_getAttributeConditionSql($condition['attribute'], $condition, $joinType);
           }
            $conditionSql = '('.join(') OR (', $sqlArr).')';
            $this->getSelect()->where($conditionSql);
            return $this;
        }
    

    添加FieldToFilter 在里面 Varien_Data_Collection_Db 只是将字段添加到 where 没有测试数组。


    编辑

    添加属性筛选器 Collection.php 在下面 Model\mysql4\News\ Mage_Eav_Model_Entity_Collection_Abstract

    嗯,

        2
  •  1
  •   Community CDub    8 年前

    也许这篇文章能帮上忙: Match as OR .

        3
  •  0
  •   R T    12 年前

    $collection->addFieldToFilter(
        array('first_name','last_name'),
        array($post['firstName'],$post['lastName'])             
    );
    

    当我打印sql时,这是有效的(这只是打印的整个语句的一部分):

    ((first_name = 'r') OR (last_name = 't'))
    

    现在我正在努力了解如何使用 'like' = .

    希望有帮助。