Yii2使用AND和OR分组循环

时间:2017-02-08 09:33:26

标签: mysql sql yii2 where

我有一个关键字"示例查询"和 我喜欢这样查询

  

SELECT * FROM项目WHERE (FLAG=1 and STATUS=1)(NAMA_PROJECT like '%example query%' or DESCRIPTION_PROJECT like '%example query%' or NAMA_PROJECT like '%example%' or NAMA_PROJECT like '%query%') ORDER   通过WAKTU_POST;

我已经尝试了这个,但它给了我一些我不想要的查询。

$query=Project::find()->where(['FLAG'=>1,'STATUS'=>1])
->andFilterWhere(['like','NAMA_PROJECT',$q])
->andFilterWhere(['like','DESCRIPTION_PROJECT',$q]);
$words=\yii\helpers\BaseStringHelper::explode($q,$delimiter=' ');
foreach($words as $word){
    $query->orWhere(['like','NAMA_PROJECT',$word]);
}

是否可以在条件内部有一个循环?

2 个答案:

答案 0 :(得分:2)

$words = \yii\helpers\BaseStringHelper::explode($q,$delimiter=' ');

$condition[] = 'OR';
$condition[] = ['like','NAMA_PROJECT',$q];
$condition[] = ['like','DESCRIPTION_PROJECT',$q];
foreach($words as $word){
    $condition[] = ['like','NAMA_PROJECT',$word];
}

$query = Project::find()
    ->where(['FLAG' => 1, 'STATUS' => 1])
    ->andWhere($condition)
    ->orderBy(['WAKTU_POST' => SORT_DESC])
    ->all();

答案 1 :(得分:0)

您可以尝试这样

Project::find()
        ->where("(FLAG=1 and STATUS=1) AND 
     ((NAMA_PROJECT like '%example query%' OR DESCRIPTION_PROJECT like '%example query%' OR NAMA_PROJECT like '%example%' or NAMA_PROJECT like '%query%')")
->all();

For Detail Information check this answers