Home » Php » php – how to use not null condition in YII2

php – how to use not null condition in YII2

Posted by: admin April 23, 2020 Leave a comment

Questions:

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,
       ]);
How to&Answers:

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.

Answer:

->where(['IS NOT', 'column', null]);

get

WHERE column IS NOT NULL

Answer:

One of the options will be:

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

Check official docs for where.

Answer:

    $items = BadOffer::find()->where(['OR',
                                               ['IS', 'moderator_id', (new Expression('Null'))],
                                               ['moderator_id' => $user->id],
    ]);

Answer:

use ->andWhere(['not', ['State' => null]]) or ->andWhere(['is not', 'State', null]);

Do no use :

  1. andFilterWhere, as the null will make this filter be ignored
  2. ->andWhere(['<>', 'State', null]) as it form query AND State <> null

Answer:

How to select non-empty columns in MySQL?

use LENGTH :

SELECT col1
FROM table
WHERE LENGTH(col1) > 0

Yii2 :

->andWhere(['>', 'LENGTH(col1)', 0])

Answer:

In Yii2, you can use like below

1) ->andWhere(['NOT', ['city' => null]])
2) ->andWhere(['<>', ['city' => null]])
3) ->andWhere('city IS NOT NULL')

Answer:

This work for me, but only when pass null as string

->andFilterWhere(['<>', '`city`', 'null']);