您好,登錄后才能下訂單哦!
小編給大家分享一下yii框架如何根據條件查詢,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
條件查詢
$customers = Customer::find()->where($cond)->all();
$cond就是我們所謂的條件,條件的寫法也根據查詢數據的不同存在差異,那么如何用yii2的方式來寫查詢條件呢?
[[簡單條件]]
// SQL: (type = 1) AND (status = 2). $cond = ['type' => 1, 'status' => 2] // SQL:(id IN (1, 2, 3)) AND (status = 2) $cond = ['id' => [1, 2, 3], 'status' => 2] //SQL:status IS NULL $cond = ['status' => null]
【and】:將不同的條件組合在一起,用法舉例:
//SQL:`id=1 AND id=2` $cond = ['and', 'id=1', 'id=2'] //SQL:`type=1 AND (id=1 OR id=2)` $cond = ['and', 'type=1', ['or', 'id=1', 'id=2']] //SQL:`type=1 AND (id=1 OR id=2)` //此寫法'='可以換成其他操作符,例:in like != >=等 $cond = [ 'and', ['=', 'type', 1], [ 'or', ['=', 'id', '1'], ['=', 'id', '2'], ] ]
[[or]]:
/SQL:`(type IN (7, 8, 9) OR (id IN (1, 2, 3)))` $cond = ['or', ['type' => [7, 8, 9]], ['id' => [1, 2, 3]]
[[not]]:
//SQL:`NOT (attribute IS NULL)` $cond = ['not', ['attribute' => null]]
[[between]]: not between 用法相同
//SQL:`id BETWEEN 1 AND 10` $cond = ['between', 'id', 1, 10]
[[in]]: not in 用法類似
//SQL:`id IN (1, 2, 3)` $cond = ['in', 'id', [1, 2, 3]] or $cond = ['id'=>[1, 2, 3]]
//IN條件也適用于多字段 $cond = ['in', ['id', 'name'], [['id' => 1, 'name' => 'foo'], ['id' => 2, 'name' => 'bar']]] //也適用于內嵌sql語句 $cond = ['in', 'user_id', (new Query())->select('id')->from('users')->where(['active' => 1])]
[[like]]:
//SQL:`name LIKE '%tester%'` $cond = ['like', 'name', 'tester'] //SQL:`name LIKE '%test%' AND name LIKE '%sample%'` $cond = ['like', 'name', ['test', 'sample']] //SQL:`name LIKE '%tester'` $cond = ['like', 'name', '%tester', false]
[[exists]]: not exists用法類似
//SQL:EXISTS (SELECT "id" FROM "users" WHERE "active"=1) $cond = ['exists', (new Query())->select('id')->from('users')->where(['active' => 1])]
此外,您可以指定任意運算符如下:
//SQL:`id >= 10` $cond = ['>=', 'id', 10] //SQL:`id != 10` $cond = ['!=', 'id', 10]
以上是“yii框架如何根據條件查詢”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。