Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chaining orX in Doctrine2 query builder

I have to dynamically add OR expressions to the query builder returned by getListQueryBuilder, right after adding a where clause. I can't find any suitable way of doing this, i'm just started learning Doctrine.

How can i "chain" a given number of orX and add them to my builder?

public function getListQueryBuilder($ownerId)
{
    $qb = $this->createQueryBuilder('t');

    return $qb
        ->where($qb->expr()->eq('t.user', ':user'))
        ->setParameter('user', $ownerId);
}

$builder = getListQueryBuilder(4);

// $ORs is a dynamically builded array, here is just an example
$ORs = array();
$ORs[] = $builder->expr()->like("t.name", 'my name');
$ORs[] = $builder->expr()->like("t.description", 'desc');

// Adding ORs to the builder
$builder->andWhere($builder->expr()->orX(/* here */));
like image 291
gremo Avatar asked Mar 22 '12 00:03

gremo


People also ask

Is Query builder an ORM?

The ORM's query builder provides a simple to use fluent interface for creating and running queries. By composing queries together, you can create advanced queries using unions and subqueries with ease.

How does query builder work?

Using Query Builder, you can search and filter database objects, select objects and columns, create relationships between objects, view formatted query results, and save queries with little or no SQL knowledge.

What is Query builder in C#?

SQL query builder, written in c#, helps you build complex queries easily, supports SqlServer, MySql, PostgreSql, Oracle, Sqlite and Firebird. sqlkata.com.

What is Query builder in Java?

The query builder is a utility to generate CQL queries programmatically.


2 Answers

You can check this solution:

$orX = $builder->expr()->orX();
foreach($ORs as $or) {
    $orX->add($or);
}
$builder->andWhere($orX);
like image 65
Philippe Avatar answered Sep 19 '22 14:09

Philippe


I stumbled on the same problem and tried :

$builder->andWhere($builder->expr()->orX($ORs));

but it does not work since orX calls "return new Expr\Orx(func_get_args());" internally and you end up with something like array(array(or1, or2))

having looked at the API however i figured you can do this:

$builder->andWhere($builder->expr()->orX()->addMultiple($ORs));

OR do use $ORs table at all but issue:

$orx = $builder->expr()->orX();
$orx->add($builder->expr()->like("t.name", 'my name'));
$orx->add($builder->expr()->like("t.description", 'desc'));
$builder->andWhere($orx);
like image 31
sparrow Avatar answered Sep 20 '22 14:09

sparrow