2013-03-05 73 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);