doctrine FindBy method with 'OR condition'?

后端 未结 2 1297
醉梦人生
醉梦人生 2021-01-21 00:32

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

I want That the output Be like this :

SELECT * FROM `f         


        
2条回答
  •  难免孤独
    2021-01-21 01:01

    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

提交回复
热议问题