Skip to content
Advertisement

how to use not null condition in YII2

Hi i want to use not null condition in my yii2 query how should i use that. i don’t want city and state null.

My query is

$query = new Query;             
      $query->select('ID, City,State,StudentName')                                  
                                ->from('student')                               
                                ->where(['IsActive' => 1])                                                                                                          
                                ->orderBy(['rand()' => SORT_DESC])
                                ->limit(10);                                
    $dataProvider = new ActiveDataProvider([
        'query' => $query,
        'pagination' => false,
       ]);

Advertisement

Answer

You can use the not operator combined with the fields that should not be null to generate a IS NOT NULL SQL statement. Like this:

$query = new Query;             
$query->select('ID, City,State,StudentName')
      ->from('student')                               
      ->where(['IsActive' => 1])
      ->andWhere(['not', ['City' => null]])
      ->andWhere(['not', ['State' => null]])
      ->orderBy(['rand()' => SORT_DESC])
      ->limit(10);

Also check the examples in the documentation.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement