GenkaiG
GenkaiG

Reputation: 5

Yii2 using where AND and OR grouping with looping

I have a keyword "example query" and I like to query like this

SELECT * FROM project 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%') ORDER BY WAKTU_POST;

I already try this but it give me the query I didn't want.

$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]);
}

Is it possible to have a loop inside where condition?

Upvotes: 0

Views: 899

Answers (2)

Insane Skull
Insane Skull

Reputation: 9358

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

Upvotes: 3

Amitesh Kumar
Amitesh Kumar

Reputation: 3079

You can try Like this

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

Upvotes: 0

Related Questions