doctrine FindBy method with 'OR condition'?

不问归期 提交于 2019-12-20 02:49:07

问题


Is it possible to use OR statement in Doctrine findBy() method?

I want That the output Be like this :

SELECT * FROM `friends` WHERE userId=1 OR FriendId=1 ;

The code Now :

$user = $repository->findBy(array(
            'userId' => $this->getRequest()->getSession()->get('id')
    );

回答1:


I would just use DQL... Add a function like this to your repository:

public function findFriends($userId)
{
    return $this->getEntityManager()
        ->createQuery('SELECT f FROM Friends WHERE userId = :userId OR FriendId = :userId')
        ->setParameter('userId', $userId)
        ->getOneOrNullResult();
}

Or use the query builder instead of DQL:

public function findFriends($userId)
{
    return $this->getEntityManager()
        ->createQueryBuilder()
        ->from('Friends', 'f')
        ->where('f.userId = :userId')
        ->orWhere('f.friendId = :userId')
        ->setParameter('userId', $userId)
        ->getQuery()
        ->getOneOrNullResult();
}

And then just use:

$user = $repository->findFriends($this->getRequest()->getSession()->get('id'));



回答2:


MongoDB specific syntax

You can use the $or and $and keys in the array you pass to findBy:

$id = $this->getRequest()->getSession()->get('id');
$user = $repo->findBy(
    array(
        '$or' => array(
            array('userId' => $id),
            array('FriendId' => $id),
        ),
    );
);

Using QueryBuilder:

But seeing as this is mongoDB specific, this probably doesn't answer your question. Using the queryBuilder, you could just write this:

$qb = $repository->createQueryBuilder();
$qb->select('f')
    ->from('friends', 'f')//replace friends with the correct entity name
    ->where('f.userId = :uid')
    ->orWhere('f.FriendId = :fid')
    ->setParameter('uid', $id)
    ->setParameter('fid', $id);
$users = $qb->getQuery()->getSingleResult();//or more

You could build the or clause using querybuilder expressions instead, that would look something like this:

$qb->where(
        $qb->expr()->orX(
            $qb->expr()->eq('f.userId', ':uid'),
            $qb->expr()->eq('f.FriendId', ':fid')
        )
    )
    ->setParameter('uid', $id)
    ->setParameter('fid', $id);

Here's some more info

Even though you're using the same value twice, you have to call setParameter twice. The reason for this can be found here

Lastly, some more docs on the QueryBuilder class



来源:https://stackoverflow.com/questions/34003492/doctrine-findby-method-with-or-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!