I want to create a rather complex and flexible query with Doctrines Criteria
. I have an andWhere
that is included in every query, but then (depending on input) I want to add some optinal parameters with orWhere
.
$criteria = Criteria::create();
/* Add Criteria for last 55 Days (every query) */
$criteria->where(Criteria::expr()->gte('gameCreation', $long));
/* Gather optional Params */
$orxList = array();
/* Optional Criteria */
if (!empty($champions)) {
foreach ($champions as $c) {
$orxList[] = Criteria::expr()->eq('champion',$c);
}
}
...
$criteria->andWhere(Criteria::expr()->orX($orxList));
This leads to an Exception:
No expression given to CompositeExpression.
How would I combine such a Criteria with the initial where
clause?
You should use orX()
from Expr class for this, example:
$orX = $exp->orX();
$index = 0;
foreach ($champions as $c) {
$paramName = ':param_' . $index;
$orX->add($qb->expr()->eq('u.column', $paramName));
$qb->setParameter($paramName, $c);
$index++;
}
However, if your array are just plain strings/object compared in the same way, consider using WHERE IN [] expression.
I faced a similar problem and solved it like this:
use Doctrine\Common\Collections\Expr\CompositeExpression;
...
/* Gather optional Params */
$orxList = array();
/* Optional Criteria */
if (!empty($champions)) {
foreach ($champions as $c) {
$orxList[] = Criteria::expr()->eq('champion', $c);
}
}
...
$criteria->andWhere(new CompositeExpression(CompositeExpression::TYPE_OR, $orxList));
As you see the constructor of CompositeExpression
accepts an array of expressions and this generates the correct query.