doctrine FindBy方法与'OR条件'? [英] doctrine FindBy method with 'OR condition'?

查看:360
本文介绍了doctrine FindBy方法与'OR条件'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我想要输出如下:

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

代码现在:

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


推荐答案

MongoDB特定语法



您可以使用 $或 $和您传递给 findBy 的数组中的键:

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),
        ),
    );
);



使用QueryBuilder:



但是看到这是mongoDB具体的,这可能不会回答你的问题。使用queryBuilder你可以写这个:

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

您可以使用querybuilder表达式来构建子句,看起来像这样:

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);

这里有一些更多的信息

即使你使用相同的值两次,你必须调用 setParameter 两次。 可以在这里找到原因

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

最后,还有一些文档 QueryBuilder class 中的nofollow>

Lastly, some more docs on the QueryBuilder class

这篇关于doctrine FindBy方法与'OR条件'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆