Question

I have a query that filters a list of products by a price similarity like this:

$query->andWhere(
  '(
    (i.price > ? AND i.price < ?)
    OR (i.salePrice > ? AND i.salePrice < ?)
  )',
  array(
    $item->price*0.8,
    $item->price*1.5,
    $item->salePrice*0.8,
    $item->salePrice*1.5
  )
);

Unfortunately Doctrine is ignoring outer parenthesis and instead of:

SELECT * FROM `items` WHERE `deleted`=0 AND ( 
    (`price` > ? AND `price` < ?) OR (`saleprice` > ? AND `saleprice < ?`)
)

I get something like this:

SELECT * FROM `items` WHERE `deleted`=0 AND (`price` > ? AND `price` < ?) OR (`saleprice` > ? AND `saleprice < ?`)

I.e. even deleted products with sale price that fits the condition appear in the results.

Right now I am just using single OR condition, then it works:

$query->andWhere(
  '(i.price > ? AND i.price < ?)',
  array(
    $item->price*0.8,
    $item->price*1.5
  )
);

The resulting SQL looks like this:

 SELECT * FROM `items` WHERE `deleted`=0 AND `price` > ? AND `price` < ?

But obviously this is a bit weak. How to hold multiple OR conditions together?

Was it helpful?

Solution

After trying to patch Doctrine with whereParenWrap() function from here I had to look for another solution as this simply didn't work out. It just wrapped all WHEREs in parenthesis.

The solution was simple, I just added AND TRUE to the query outside the parentheses:

$query->andWhere(
  '(
    (i.price > ? AND i.price < ?)
    OR (i.salePrice > ? AND i.salePrice < ?)
  ) AND TRUE',
  ...
);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top