在yii2中用多个where条件写查询

时间:2016-07-09 11:59:35

标签: php mysql yii2

普通php中的

查询是

$p = "SELECT * FROM followusers WHERE (follower='$followed1 and
    followed='$follower1') or (follower='$follower1' and 
    followed='$followed1')"

我在yii2中写过的查询是

 $y = Followusers::find()->where(['follower' => $userid ] and
 ['followed' => $conid])->orwhere(['followed' => $userid ] and
 ['follower' => $conid])-> all();

但是我没有在yii2

中获得查询所需的结果

3 个答案:

答案 0 :(得分:2)

尝试这种方式:

Followusers::find()->where(['follower' => $userid])    
   ->andWhere(['followed' => $conid])
   ->orwhere(['AND',
        ['followed' => $userid], 
        ['follower' => $conid]
    ])
   -> all();

答案 1 :(得分:0)

您的代码中似乎有一些语法错误,请尝试按以下格式进行格式化:

$y = Followusers::find()
     ->where(['follower' => $userid, 'followed' => $conid])
     ->orwhere(['followed' => $userid, 'follower' => $conid])
     ->all();

答案 2 :(得分:0)

如果followusers表模型是FollowUsers(在当前命名空间中,否则你必须以命名空间为前缀),你可以

$data = FollowUsers::find()
->where(['AND', 'follower='.$followed1, 'followed='.$follower1])
->orWhere(['AND', 'follower='.$follower1, 'followed='.$followed1])
->all();

否则,您可以使用参数:

$data = FollowUsers::find()
->where('(follower=:followed1 AND followed=:follower1) OR (follower=:follower1 AND followed=:followed1)', [':followed1' => $followed1, ':follower1' => $follower1])
->all();