1、簡介
資料庫查詢構建器提供了一個方便的、平滑的介面來建立和運行資料庫查詢。查詢構建器可以用於執行應用中大部分資料庫操作,並且能夠在支援的所有資料庫系統上工作。
注意:Laravel 查詢構建器使用 PDO 參數綁定來避免 SQL 插入式攻擊,不再需要過濾傳遞到綁定的字串。
2、擷取結果集
從一張表中取出所有行
在查詢之前,使用 DB門面的 table方法, table方法為給定表返回一個查詢構建器,允許你在查詢上連結更多約束條件並最終返回查詢結果。在本例中,我們使用 get方法擷取表中所有記錄:
get(); return view('user.index', ['users' => $users]); }}
和原生查詢一樣, get方法返回結果集的數組,其中每一個結果都是PHP對象的 StdClass執行個體。你可以像訪問對象的屬性一樣訪問列的值:
foreach ($users as $user) { echo $user->name;}
從一張表中擷取一行/一列
如果你只是想要從資料表中擷取一行資料,可以使用 first方法,該方法將會返回單個 StdClass對象:
$user = DB::table('users')->where('name', 'John')->first();echo $user->name;
如果你不需要完整的一行,可以使用value方法從結果中擷取單個值,該方法會直接返回指定列的值:
$email = DB::table('users')->where('name', 'John')->value('email');
從一張表中擷取組塊結果集
如果你需要處理成千上百條資料庫記錄,可以考慮使用 chunk方法,該方法一次擷取結果集的一小塊,然後填充每一小塊資料到要處理的閉包,該方法在編寫處理大量資料庫記錄的 Artisan 命令的時候非常有用。比如,我們可以將處理全部 users 表資料處理成一次處理 100 記錄的小組塊:
DB::table('users')->chunk(100, function($users) { foreach ($users as $user) { // }});
你可以通過從閉包函數中返回false來中止組塊的運行:
DB::table('users')->chunk(100, function($users) { // 處理結果集... return false;});
擷取資料列值列表
如果想要擷取包含單個列值的數組,可以使用 lists方法,在本例中,我們擷取所有 title的數組:
$titles = DB::table('roles')->lists('title');foreach ($titles as $title) { echo $title;}
在還可以在返回數組中為列值指定更多的自訂鍵(該自訂鍵必須是該表的其它欄位列名,否則會報錯):
$roles = DB::table('roles')->lists('title', 'name');foreach ($roles as $name => $title) { echo $title;}
彙總函式
隊列構建器還提供了很多彙總方法,比如 count, max, min, avg, 和 sum,你可以在構造查詢之後調用這些方法:
$users = DB::table('users')->count();$price = DB::table('orders')->max('price');
當然,你可以聯合其它查詢子句和彙總函式來構建查詢:
$price = DB::table('orders') ->where('finalized', 1) ->avg('price');
3、查詢(Select)
指定查詢子句
當然,我們並不總是想要擷取資料表的所有列,使用 select方法,你可以為查詢指定自訂的 select子句:
$users = DB::table('users')->select('name', 'email as user_email')->get();
distinct方法允許你強制查詢返回不重複的結果集:
$users = DB::table('users')->distinct()->get();
如果你已經有了一個查詢構建器執行個體並且希望添加一個查詢列到已存在的 select子句,可以使用 addSelect方法:
$query = DB::table('users')->select('name');$users = $query->addSelect('age')->get();
原生運算式
有時候你希望在查詢中使用原生運算式,這些運算式將會以字串的形式注入到查詢中,所以要格外小心避免被 SQL 注入。想要建立一個原生運算式,可以使用 DB::raw方法:
$users = DB::table('users') ->select(DB::raw('count(*) as user_count, status')) ->where('status', '<>', 1) ->groupBy('status') ->get();
4、串連(Join)
內串連(等值串連)
查詢構建器還可以用於編寫基本的SQL“內串連”,你可以使用查詢構建器執行個體上的 join方法,傳遞給 join方法的第一次參數是你需要串連到的表名,剩餘的其它參數則是為串連指定的列約束,當然,正如你所看到的,你可以在單個查詢中串連多張表:
$users = DB::table('users') ->join('contacts', 'users.id', '=', 'contacts.user_id') ->join('orders', 'users.id', '=', 'orders.user_id') ->select('users.*', 'contacts.phone', 'orders.price') ->get();
左串連
如果你是想要執行“左串連”而不是“內串連”,可以使用 leftJoin方法。該方法和 join方法的使用方法一樣:
$users = DB::table('users') ->leftJoin('posts', 'users.id', '=', 'posts.user_id') ->get();
進階串連語句
你還可以指定更多的進階串連子句,傳遞一個閉包到 join方法作為該方法的第2個參數,該閉包將會返回允許你指定 join子句約束的 JoinClause對象:
DB::table('users') ->join('contacts', function ($join) { $join->on('users.id', '=', 'contacts.user_id')->orOn(...); }) ->get();
如果你想要在串連中使用“where”風格的子句,可以在查詢中使用 where和 orWhere方法。這些方法將會將列和值進行比較而不是列和列進行比較:
DB::table('users') ->join('contacts', function ($join) { $join->on('users.id', '=', 'contacts.user_id') ->where('contacts.user_id', '>', 5); }) ->get();
5、聯合(Union)
查詢構建器還提供了一條“聯合”兩個查詢的捷徑,比如,你要建立一個獨立的查詢,然後使用 union方法將其和第二個查詢進行聯合:
$first = DB::table('users') ->whereNull('first_name');$users = DB::table('users') ->whereNull('last_name') ->union($first) ->get();
unionAll方法也是有效,並且和 union有同樣的使用方法。
6、Where子句
簡單where子句
使用查詢構建器上的 where方法可以添加 where子句到查詢中,調用 where最基本的方法需要三個參數,第一個參數是列名,第二個參數是一個資料庫系統支援的任意操作符,第三個參數是該列要比較的值。
例如,下面是一個驗證“votes”列的值是否等於100的查詢:
$users = DB::table('users')->where('votes', '=', 100)->get();
為了方便,如果你只是簡單比較列值和給定數值是否相等,可以將數值直接作為 where方法的第二個參數:
$users = DB::table('users')->where('votes', 100)->get();
當然,你可以使用其它操作符來編寫 where子句:
$users = DB::table('users') ->where('votes', '>=', 100) ->get();$users = DB::table('users') ->where('votes', '<>', 100) ->get();$users = DB::table('users') ->where('name', 'like', 'T%') ->get();
or
你可以通過方法鏈將多個 where約束連結到一起,也可以添加 or子句到查詢, orWhere方法和 where方法接收參數一樣:
$users = DB::table('users') ->where('votes', '>', 100) ->orWhere('name', 'John') ->get();
更多Where子句
whereBetween
whereBetween方法驗證列值是否在給定值之間:
$users = DB::table('users') ->whereBetween('votes', [1, 100])->get();
whereNotBetween
whereNotBetween方法驗證列值不在給定值之間:
$users = DB::table('users') ->whereNotBetween('votes', [1, 100]) ->get();
whereIn/whereNotIn
whereIn方法驗證給定列的值是否在給定數組中:
$users = DB::table('users') ->whereIn('id', [1, 2, 3]) ->get();
whereNotIn方法驗證給定列的值不在給定數組中:
$users = DB::table('users') ->whereNotIn('id', [1, 2, 3]) ->get();
whereNull/whereNotNull
whereNull方法驗證給定列的值為NULL:
$users = DB::table('users') ->whereNull('updated_at') ->get();
whereNotNull方法驗證給定列的值不是NULL:
$users = DB::table('users') ->whereNotNull('updated_at') ->get();
進階Where子句
參數 分組
有時候你需要建立更加進階的 where子句比如“where exists”或者嵌套的參數分組。Laravel查詢構建器也可以處理這些。作為開始,讓我們看一個在括弧中進行分組約束的例子:
DB::table('users') ->where('name', '=', 'John') ->orWhere(function ($query) { $query->where('votes', '>', 100) ->where('title', '<>', 'Admin'); }) ->get();
正如你所看到的,傳遞閉包到 orWhere方法構造查詢構建器來開始一個約束分組,,該閉包將會擷取一個用於設定括弧中包含的約束的查詢構建器執行個體。上述語句等價於下面的SQL:
select * from users where name = 'John' or (votes > 100 and title <> 'Admin')
exists語句
whereExists方法允許你編寫 where existSQL子句, whereExists方法接收一個閉包參數,該閉包擷取一個查詢構建器執行個體從而允許你定義放置在“exists”子句中的查詢:
DB::table('users') ->whereExists(function ($query) { $query->select(DB::raw(1)) ->from('orders') ->whereRaw('orders.user_id = users.id'); }) ->get();
上述查詢等價於下面的SQL語句:
select * from userswhere exists ( select 1 from orders where orders.user_id = users.id)
7、排序、分組、限定
orderBy
orderBy方法允許你通過給定列對結果集進行排序, orderBy的第一個參數應該是你希望排序的列,第二個參數控制著排序的方向——asc或desc:
$users = DB::table('users') ->orderBy('name', 'desc') ->get();
groupBy / having / havingRaw
groupBy和 having方法用於對結果集進行分組, having方法和 where方法的用法類似:
$users = DB::table('users') ->groupBy('account_id') ->having('account_id', '>', 100) ->get();
havingRaw方法可以用於設定原生字串作為 having子句的值,例如,我們要找到所有售價大於 $2500的部分:
$users = DB::table('orders') ->select('department', DB::raw('SUM(price) as total_sales')) ->groupBy('department') ->havingRaw('SUM(price) > 2500') ->get();
skip / take
想要限定查詢返回的結果集的數目,或者在查詢中跳過給定數目的結果,可以使用 skip和 take方法:
$users = DB::table('users')->skip(10)->take(5)->get();
8、插入(Insert)
查詢構建器還提供了 insert方法來插入記錄到資料表。 insert方法接收數組形式的列名和值進行插入操作:
DB::table('users')->insert( ['email' => 'john@example.com', 'votes' => 0]);
你甚至可以一次性通過傳入多個數組來插入多條記錄,每個數組代表要插入資料表的記錄:
DB::table('users')->insert([ ['email' => 'taylor@example.com', 'votes' => 0], ['email' => 'dayle@example.com', 'votes' => 0]]);
自增ID
如果資料表有自增ID,使用 insertGetId方法來插入記錄將會返回ID值:
$id = DB::table('users')->insertGetId( ['email' => 'john@example.com', 'votes' => 0]);
注意:當使用 PostgresSQL時 insertGetId方法預設自增列被命名為 id,如果你想要從其他“序列”擷取ID,可以將序列名作為第二個參數傳遞到 insertGetId方法。
9、更新(Update)
當然,除了插入記錄到資料庫,查詢構建器還可以通過使用 update方法更新已有記錄。 update方法和 insert方法一樣,接收列和值的索引值對數組包含要更新的列,你可以通過 where子句來對 update查詢進行約束:
DB::table('users') ->where('id', 1) ->update(['votes' => 1]);
增加/減少
查詢構建器還提供了方便增減給定列名數值的方法。相較於編寫 update語句,這是一條捷徑,提供了更好的體驗和測試介面。
這兩個方法都至少接收一個參數:需要修改的列。第二個參數是可選的,用於控制列值增加/減少的數目。
DB::table('users')->increment('votes');DB::table('users')->increment('votes', 5);DB::table('users')->decrement('votes');DB::table('users')->decrement('votes', 5);
在操作過程中你還可以指定額外的列進行更新:
DB::table('users')->increment('votes', 1, ['name' => 'John']);
10、刪除(Delete)
當然,查詢構建器還可以通過 delete方法從表中刪除記錄:
DB::table('users')->delete();
在調用 delete方法之前可以通過添加 where子句對 delete語句進行約束:
DB::table('users')->where('votes', '<', 100)->delete();
如果你希望清除整張表,也就是刪除所有列並將自增ID置為0,可以使用 truncate方法:
DB::table('users')->truncate();
11、悲觀鎖
查詢構建器還包含一些方法協助你在select語句中實現“悲觀鎖”。可以在查詢中使用 sharedLock方法從而在運行語句時帶一把”共用鎖定“。共用鎖定可以避免被選擇的行被修改直到事務提交:
DB::table('users')->where('votes', '>', 100)->sharedLock()->get();
此外你還可以使用 lockForUpdate方法。“for update”鎖避免選擇行被其它共用鎖定修改或刪除:
DB::table('users')->where('votes', '>', 100)->lockForUpdate()->get();