簡體   English   中英

如何在 YII2 中使用非空條件

[英]how to use not null condition in YII2

嗨,我想在我的 yii2 查詢中使用非空條件,我應該如何使用它。 我不希望城市和州為空。

我的查詢是

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

您可以將not運算符與不應為 null 的字段結合使用以生成IS NOT NULL SQL 語句。 像這樣:

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

還要檢查文檔中的示例。

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

得到

WHERE column IS NOT NULL

也可以用,打字比較快

->where('column IS NOT NULL')

在復雜查詢中

->where(['AND',
  'column1 IS NOT NULL', // works
  ['IS NOT', 'column2', null], // works
  ['column3' => $value],
)

選項之一是:

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

檢查官方文檔的位置

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

使用->andWhere(['not', ['State' => null]])->andWhere(['is not', 'State', null]);

不要使用:

  1. andFilterWhere ,因為null會使這個過濾器被忽略
  2. ->andWhere(['<>', 'State', null])因為它形成查詢AND State <> null

在 Yii2 中,我們可以使用以下任何查詢來驗證空條件,

->andWhere(['NOT', ['city' => null]]);

或者

->andWhere(['<>', ['city' => null]]);

或者

->andWhere('city IS NOT NULL');

如何在 MySQL 中選擇非空列?

使用長度

SELECT col1
FROM table
WHERE LENGTH(col1) > 0

一二:

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

這對我有用,但僅當將 null 作為字符串傳遞時

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM