Search code examples
mysqlconditional-statementsparenthesespimcore

Subconditions for objectlist query with order for "and" and "or"


I would like to filter results with several parameters: a boolean status, a category, and a keyword that would be search either on the title or the description (localized fields).

I am a newbie for this. I succeeded to make the query work when I ommit the description keyword criteria :

$advertList = new Object\Advert\Listing();
$advertList->setOrderKey("date");
$advertList->setOrder("DESC");
$conditions = [];
if ($this->getParam("keyword")) 
  {
     $conditions[] = " title LIKE " . $advertList->quote("%" . $this->getParam("keyword") . "%");
  }
if ($this->getParam("reqoffer")) {
    $conditions[] = "reqoffer LIKE " . $advertList->quote("%" . $this->getParam("reqoffer") . "%");    
} 
if($this->getParam("category")) {
    $conditions[] = "category__id = " . $this->getParam("category");
}  
$advertList->setCondition(implode(" AND ", $conditions));  

But when I want to add my "or condtion" :

$conditions[] = "( title LIKE " . $advertList->quote("%" . $this->getParam("keyword") . "%") . 
               //        " OR shorttext LIKE " . $advertList->quote("%" . $this->getParam("keyword") . "% )");

I can't succeed to make my firt query on the keyword in parenthesis for the "OR" : I mean at the end, I get results even if category or reqoffer is wrong as long as title is ok...

I have been looking for many hours and tried many things. I could not find the same issue. I am sure this is obvious for some of you. Please help if you can.

Thanks in advance.


Solution

  • If you want to build conditions like WHERE (a AND b) OR c you need to do something like this (pseudo-code):

    $or_conditions = [];
    $and_conditions = [];
    if (needA)
      $and_conditions[] = "a";
    if (needB)
      $and_conditions[] = "b";
    $or_conditions[] = "(" . implode(" AND ", $and_conditions) . ")";
    $advertList->setCondition(implode(" OR ", $or_conditions));