Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

doctrine2 findby two columns OR condition

My action:

   $matches_request = $em->getRepository('Bundle:ChanceMatch')->findByRequestUser(1);
   $matches_reply = $em->getRepository('Bundle:ChanceMatch')->findByReplyUser(1);

Is it possible to join the querys with an or condition with getRepository, eg.

$matches_reply = $em->getRepository('FrontendChancesBundle:ChanceMatch')->findBy(array('requestUser' => 1, 'replyUser' => 1); 
//this of course gives me the a result when `requestUser` and `replyUser` is `1`. 

My table

id | requestUser | replyUser
....
12 |      1      |     2
13 |      5      |     1

My query should return the id 12 & 13.

Thanks for help!

like image 670
craphunter Avatar asked Mar 05 '13 16:03

craphunter


2 Answers

You can use QueryBuilder or create a custom repository for that entity and create a function that internally use QueryBuilder.

$qb = $em->getRepository('FrontendChancesBundle:ChanceMatch')->createQueryBuilder('cm');
$qb
    ->select('cm')
    ->where($qb->expr()->orX(
        $qb->expr()->eq('cm.requestUser', ':requestUser'),
        $qb->expr()->eq('cm.replyUser', ':replyUser')
    ))
    ->setParameter('requestUser', $requestUserId)
    ->setParameter('replyUser', $replyUserId)
;
$matches_reply = $qb->getQuery()->getSingleResult();
// $matches_reply = $qb->getQuery()->getResult(); // use this if there can be more than one result

For more information on custom Repository see official documentation:

http://symfony.com/doc/2.0/book/doctrine.html#custom-repository-classes

like image 151
tomas.pecserke Avatar answered Nov 18 '22 08:11

tomas.pecserke


It's possible to use Criteria for the complex queries with getRepository():

$criteria = new \Doctrine\Common\Collections\Criteria();
$criteria
  ->orWhere($criteria->expr()->contains('domains', 'a'))
  ->orWhere($criteria->expr()->contains('domains', 'b'));

$domain->ages = $em
  ->getRepository('Group')
  ->matching($criteria);
like image 25
gorodezkiy Avatar answered Nov 18 '22 07:11

gorodezkiy