Search code examples
sqlsymfonydoctrine-ormdql

Multiple condition inside a DQL query


I need to build a SQL/DQL query for my dating website, which retrieve all users with some matched fields like sex, age, location and 3 interests. I don't know how to create multiple condition inside my DQL Query. I've started with something like that:

SELECT u FROM MyUserBundle:User u WHERE u.sex LIKE :preference"); $query->setParameters(array('preference' => '%' . $preference . '%' 'age' => '%' . $age . '%' 'location' => '%' . $location . '%' 'interest' => '%' . $interests . '%')); $users = $query->getResult();

I'm using Symfony2 and Doctrine2 and it doesn't work for me. Someone can show me how to manage multiple condition inside my query ? Thanks for your help!


Solution

  • In case of more sophisticated queries, better use Doctrine2 Query Builder

    $qb =  $this->getDoctrine()->getEntityManager()->createQueryBuilder();
    
    $qb
       ->select('u')
       ->from('MyUserBundle:User', 'u')
       ->where($qb->expr()->like('u.sex', ':preferense'))
       ->andWhere($qb->expr()->like('u.age', ':age'))
       ->andWhere($qb->expr()->like('u.location', ':location'))
       ->andWhere($qb->expr()->like('u.interest', ':interest'))
       ->setParameters(array(
          'preferense' => '%'.$preference.'%',
          'age' => '%'.$location.'%',
          'location' => '%'.$location.'%',
          'interest' => '%'.$interests.'%',
       ));
    
    $users = $qb->getQuery()->getResult(); 
    

    Tip: if $interests is array use foreach.