Question

I am modifying the Magento search results to include matching categories, pages and blog posts (from the free version of Neotheme nBlog). Whilst the categories and pages are working just fine there is something very odd going on with the blog posts. The posts appear to be stored in a flat, non-EAV, table.

When I do this, searching for "test":

$needleSearch = "test";
$posts = Mage::getModel("neotheme_blog/post")
                ->setStoreId($storeId)
                ->getCollection()
                ->addStoreFilter()
                ->addStatusFilter(NeoTheme_Blog_Model_Post::STATUS_ACTIVE)
                ->addPublishFilter()
                ->addFieldToFilter(
                    array(
                        array("attribute"=>"title","like"=>$needleSearch),
                        array("attribute"=>"author","like"=>$needleSearch),
                        array("attribute"=>"summary","like"=>$needleSearch)
                    )
                  ) //OR BIT
                ;

The resulting SELECT query ends up with this in the middle:

((`title`.`%test%` = '') OR (`author`.`%test%` = '') OR (`summary`.`%test%` = ''))

The nested array for the OR works fine for the EAV (categories and pages).

This also produces the same result:

            ->addFieldToFilter(
                    array(
                        array("title","like"=>$needleSearch),
                        array("author","like"=>$needleSearch),
                        array("summary","like"=>$needleSearch)
                    )
             )

Putting array() around the like bit ends with the SQL query showing

...(`title`.`array` = '') OR...

A single LIKE works:

$posts = Mage::getModel("neotheme_blog/post")
                ->setStoreId($storeId)
                ->getCollection()
                ->addStoreFilter()
                ->addFieldToFilter( 'title', array('like'=>$needleSearch) )
;

I was wondering if anyone had any idea of what might be going on? I can't find an override of addFieldToFilter() in the module.

Thanks

Was it helpful?

Solution

The correct syntax to combine conditions of different fields with OR is:

->addFieldToFilter(
    array(
        'title',
        'author',
        'summary'
    ),
    array(
        array('like' => $needleSearch),
        array('like' => $needleSearch),
        array('like' => $needleSearch),
    )
);

i.e. to pass an array of fields an and array of conditions. The elements of these arrays with the same keys will be treated as if they were passed as single parameters.

OTHER TIPS

Have you tried something like this?

$collection
    ->getSelect()
    ->where("(something like 'abc') OR (something_else LIKE 'doremi')");

PS: you should worry about sql injection

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top