user3703456
user3703456

Reputation:

Symfony2/Doctrin2 search with optional parameters

I have a form with 2 fields: name, age, each is optional. How can I search in database with optional parameters?

$this->getDoctrine->getRepository('DbBundle:Users')->findBy(array('name' => $name, 'age' => $age)); 

Return nothing if name or age is empty.

Upvotes: 0

Views: 621

Answers (1)

Raphaël Malié
Raphaël Malié

Reputation: 4002

You can create a DQL query. You can see the documentation of DQL here : http://doctrine-orm.readthedocs.org/en/latest/reference/dql-doctrine-query-language.html

For example, you can do that :

$qb = $this->getDoctrine->createQueryBuilder();
$qb->select('u');
$qb->from('DbBundle:Users', 'u');

if ($name){
   $qb->andWhere('name = :name')->setParameter('name', $name);
}

if ($age){
   $qb->andWhere('age = :age')->setParameter('age', $age);
}

$users = $qb->getQuery()->getResult();

You can also keep the repository way, you only need to populate the array with available vars :

$findByData = [];
if ($name){
   $findByData['name'] = $name;
}

if ($age){
   $findByData['age'] = $age;
}

// Avoid error if $age and $name are empty
if (count($findByData) == 0){
   throw new \Exception('Error ...');
}

$users = $this->getDoctrine->getRepository('DbBundle:Users')->findBy($findByData);

Upvotes: 2

Related Questions