【问题标题】:doctrine FindBy method with 'OR condition'?带有“或条件”的学说 FindBy 方法?
【发布时间】:2015-11-30 16:39:11
【问题描述】:

是否可以在 Doctrine findBy() 方法中使用 OR 语句?

我希望输出是这样的:

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

现在的代码:

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

【问题讨论】:

    标签: php symfony doctrine-orm doctrine


    【解决方案1】:

    我只会使用 DQL...将这样的函数添加到您的存储库:

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

    或者使用查询生成器代替 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();
    }
    

    然后只需使用:

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

    【讨论】:

      【解决方案2】:

      MongoDB 特定语法

      您可以在传递给findBy 的数组中使用$or$and 键:

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

      使用 QueryBuilder:

      但鉴于这是特定于 mongoDB 的,这可能无法回答您的问题。使用 queryBuilder,你可以这样写:

      $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
      

      您可以改用查询构建器表达式来构建or 子句,如下所示:

      $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

      即使您两次使用相同的值,您也必须调用setParameter 两次。 The reason for this can be found here

      最后,还有一些文档on the QueryBuilder class

      【讨论】:

      • 您是否尝试过任何一个查询?两者都行不通。
      • @Cerad:我没有,也没有注意到 OP 可能使用 MongoDB。我已经更新了答案
      • 对我来说:无法识别的字段:$或
      猜你喜欢
      • 2012-03-04
      • 1970-01-01
      • 1970-01-01
      • 2018-06-27
      • 2012-02-02
      • 1970-01-01
      • 1970-01-01
      • 2014-05-08
      • 1970-01-01
      相关资源
      最近更新 更多