Search code examples
phpmagentofiltersql-likeaddattribute

Magento "addAttributeToFilter like" with OR statement not working


I working on a Magento project, but i seriously stuck.

I want to add 2 LIKE checks in my query.

Now my code looks like this:

$this->_productCollection->addAttributeToFilter(
    array(
        array('attribute' => 'name', 'like' => '%'.$_GET["keyword"].'%'),
        array('attribute' => 'att_wine_alias', 'like' => '%'.$_GET["keyword"].'%')
    )
);

att_wine_alias: textarea with misspellings or tags

So, if i use this code, Magento didn't search in name field. And if i delete the att_wine_alias attribute from filter, name search works fine.

I want to search in both fields with "like" using OR statement.

What did I do wrong?

Thank you! // sorry for the english mistakes


Solution

  • Try with the code below and let me know if this works

    $this->_productCollection->addAttributeToFilter(
        array(
             array('attribute' => 'name', 'like' => $_GET["keyword"]),
             array('attribute' => 'att_wine_alias', 'like' => $_GET["keyword"])
        )
    );
    

    However, addFieldToFilter is also an option which works this way as below:

    ->addFieldToFilter(
        array('name', 'att_wine_alias'),
        array(
            array('like'=>'%' . $GET['keyword'] . '%'), 
            array('like'=>'%' . $GET['keyword'] . '%')
        )
     )
    

    The errors mentioned in the comments below could be because of ReIndexing. Are you using Flat tables?

    Just in case, if you are then you might want to REINDEX and then try once again.

    Also, this could be because the way the code must have been placed in the file. Will help debug it if you can share the function where you are trying to write this code.

    Hope this helps!

    Happy Coding...