学说2 findby 两列 OR 条件
问题描述:
我的行动:
$matches_request = $em->getRepository('Bundle:ChanceMatch')->findByRequestUser(1);
$matches_reply = $em->getRepository('Bundle:ChanceMatch')->findByReplyUser(1);
是否可以将带有 或
条件的查询与 getRepository 结合起来,例如.
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`.
我的桌子
id | requestUser | replyUser
....
12 | 1 | 2
13 | 5 | 1
我的查询应该返回 id 12 &13
.
感谢您的帮助!
答
您可以使用 QueryBuilder 或为该实体创建自定义存储库并创建一个在内部使用 QueryBuilder 的函数.
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