4

i have managed to do this with addFieldToFilter default functionality like this:

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

this is working when i print sql (this is just part from the whole statement being printed):

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

now i am trying to understand how to use 'like' instead of =. need some help in understanding that.

your time and answers are highly appericiated thank you.

4

3 回答 3

3

这很奇怪,但是在对您的问题进行了一些研究之后,解决方案非常简单 - 它在 Magento 代码的注释中给出:

addAttributeToFilter()Mage/Eav/Model/Entity/Collection/Abstract.php(最终被调用的)方法的注释中,您可以阅读:

/**
 * Add attribute filter to collection
 *
 * If $attribute is an array will add OR condition with following format:
 * array(
 *     array('attribute'=>'firstname', 'like'=>'test%'),
 *     array('attribute'=>'lastname', 'like'=>'test%'),
 * )
 */

我不太清楚这应该是什么意思,但它很简单:如果你想在语句中的属性之间添加一个 OR 条件,那么你必须以addAttributeToFilter()这种方式为方法提供参数,所以在你的情况:

$collection->addFieldToFilter(
array(
   array('attribute'=>'firstname', 'like'=>$post['firstName']),
   array('attribute'=>'lastname', 'like'=>$post['lastName'])
));

如果您查看方法内部,您可以遵循此addAttributeToFilter()方法:

if (is_array($attribute)) {
        $sqlArr = array();
        foreach ($attribute as $condition) {
            $sqlArr[] = $this->_getAttributeConditionSql($condition['attribute'], $condition, $joinType);
        }
        $conditionSql = '('.implode(') OR (', $sqlArr).')';
于 2013-05-25T18:30:31.313 回答
2
addFieldToFilter( 'sku', array( "like"=>'abc123' ) )

在这里您可以阅读更多关于 Magento 收藏的信息:http: //alanstorm.com/magento_collections

例如,请参阅名为“AND 或 OR,或者是 OR 和 AND?”的部分。在本文中。

于 2013-05-25T11:40:50.993 回答
2

对于您的 googlers,正确的方法是:

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

您应该传递一个字段数组和一个条件数组。

生成的 SQL:

... WHERE ((first_name LIKE '%xxxx%') OR (last_name LIKE '%yyy%')) ...
于 2015-09-04T13:15:32.210 回答