4

I have a Question, How to use Closure type Active records Query in YII2 with conditional WHERE.

Here what i want to achive:

public function getUsers($limit = 10, $type = 1, $company_id = 0) { 
    return User::find()->where( function($query) use ($type, $company_id){       
                $query->where(['type' => $type]); 
                if($company_id != 0) { 
                   $query->andWhere(['company_id' => $company_id]); 
                } 
               })
            ->orderBy([ 'created_at'=> SORT_DESC, ]) 
            ->limit($limit); 
}

Please Help if someone know about this.1

Nadeem Latif
  • 174
  • 1
  • 6

3 Answers3

5

Can't figure out what for Closure here. You can use andFilterWhere() for company_id condition, but you should set it to null as default, so this condition will be ignored if company_id wasn't initialized:

public function getUsers($limit = 10, $type = 1, $company_id = null) { 
    return User::find()
            ->where(['type' => $type])
            ->andFilterWhere(['company_id' => $company_id])
            ->orderBy([ 'created_at'=> SORT_DESC ]) 
            ->limit($limit)
            ->all(); //probably you muiss it
}

http://www.yiiframework.com/doc-2.0/yii-db-querytrait.html#andFilterWhere()-detail

user1852788
  • 4,278
  • 26
  • 25
1
public function getUsers($limit = 10, $type = 1, $company_id = null) 
{
       $query =User::find()
            ->where(['type' => $type])
            ->orderBy([ 'created_at'=> SORT_DESC ]) 
            ->limit($limit)
            ->all(); 

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

      // then filter data
      if($company_id != null)
          $query->andFilterWhere(['company_id' => $company_id]);
}
Sergey
  • 7,985
  • 4
  • 48
  • 80
0

I had the same problem in Laravel MVC and something like that was ok for me.

Replace

$query->andWhere(['company_id' => $company_id]);

with

$query->where(['company_id' => $company_id]);
Makis
  • 1,214
  • 3
  • 16
  • 40