2013-03-05 69 views
4

我的行动:doctrine2 findby两列或两条件

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

是否有可能与or条件与getRepository,例如加入querys。

$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`. 

我的表

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

我的查询应返回id 12 & 13

感谢您的帮助!

回答

11

您可以使用QueryBuilder或为该实体创建自定义存储库并创建一个内部使用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 

欲了解更多关于自定义库看到官方文档:

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

+0

谢谢!正是我想要的! – craphunter 2013-03-05 19:44:40

2

它可以使用Criteria对于复杂的查询与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);