在 CodeIgniter 4 我們建立 Query Builder Class 後,可以透過其來幫我們 where 的語法查詢,具體使用方法如下:
$builder->where()
1. 簡單的 key/value 方法:
$builder->where('name', $name); // 產生的語法: WHERE name = 'Joe'
如果有很多個 -> where 會自動幫你加上 AND 語法:
$builder->where('name', $name); $builder->where('title', $title); $builder->where('status', $status); // WHERE name = 'Joe' AND title = 'boss' AND status = 'active'
2. 客製化 key/value 方法:
在 where() 可以用第一個參數來當條件判斷:
$builder->where('name !=', $name); $builder->where('id <', $id); // 產生的語法: WHERE name != 'Joe' AND id < 45
3. 關聯陣列方法:
$array = ['name' => $name, 'title' => $title, 'status' => $status]; $builder->where($array); // 產生的語法: WHERE name = 'Joe' AND title = 'boss' AND status = 'active'
也可以加入各別的判斷:
$array = ['name !=' => $name, 'id <' => $id, 'date >' => $date]; $builder->where($array);
4. 自定字串:
$where = "name='Joe' AND status='boss' OR status='active'"; $builder->where($where);
如果要帶變數的話要 escape 避免 SQL Injection。
$name = $builder->db->escape('Joe'); $where = "name={$name} AND status='boss' OR status='active'"; $builder->where($where);
5. 子查詢
子查詢可以像這樣寫:
$builder->where('advance_amount <', function(BaseBuilder $builder) { return $builder->select('MAX(advance_amount)', false)->from('orders')->where('id >', 2); }); // 產生的語法: WHERE "advance_amount" < (SELECT MAX(advance_amount) FROM "orders" WHERE "id" > 2)
$builder->orWhere()
用 orWhere() 在把實體串起來就會變成是用 or 連接:
$builder->where('name !=', $name); $builder->orWhere('id >', $id); // 產生的語法: WHERE name != 'Joe' OR id > 50
$builder->whereIn()
產生 whrer 欄位 in 語法的:
$names = ['Frank', 'Todd', 'James']; $builder->whereIn('username', $names); // 產生的語法: WHERE username IN ('Frank', 'Todd', 'James')
使用子查詢的方法:
$builder->whereIn('id', function(BaseBuilder $builder) { return $builder->select('job_id')->from('users_jobs')->where('user_id', 3); }); // 產生的語法: WHERE "id" IN (SELECT "job_id" FROM "users_jobs" WHERE "user_id" = 3)
$builder->orWhereIn()
用 or 串接。
$names = ['Frank', 'Todd', 'James']; $builder->orWhereIn('username', $names); // 產生的語法: OR username IN ('Frank', 'Todd', 'James')
使用子查詢:
$builder->orWhereIn('id', function(BaseBuilder $builder) { return $builder->select('job_id')->from('users_jobs')->where('user_id', 3); }); // 產生的語法: OR "id" IN (SELECT "job_id" FROM "users_jobs" WHERE "user_id" = 3)
$builder->orWhereNotIn()
產生 WHERE 欄位 NOT IN ('item', 'item') 的SQL查詢語法,如果合適的話就用OR串接。
$names = ['Frank', 'Todd', 'James']; $builder->orWhereNotIn('username', $names); // 產生的語法: OR username NOT IN ('Frank', 'Todd', 'James')
使用子查詢:
$builder->orWhereNotIn('id', function(BaseBuilder $builder) { return $builder->select('job_id')->from('users_jobs')->where('user_id', 3); }); // 產生的語法: OR "id" NOT IN (SELECT "job_id" FROM "users_jobs" WHERE "user_id" = 3)