doctrine2 findby两列OR条件

时间:2013-03-05 16:54:04

标签: symfony doctrine-orm symfony-2.1

我的行动:

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

是否可以使用getRepository以or条件加入查询,例如

$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

感谢您的帮助!

2 个答案:

答案 0 :(得分:12)

您可以使用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

答案 1 :(得分:3)

可以将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);