資料庫:查詢構建器
- 簡介
- 執行資料庫查詢
- 查詢語句 (Select Statements)
- 原生表示式
- 連線 (Joins)
- 聯合查詢 (Unions)
- 基礎 Where 子句
- 高階 Where 子句
- 排序、分組、限制與偏移
- 條件子句
- 插入語句
- 更新語句
- 刪除語句
- 悲觀鎖
- 可複用的查詢元件
- 除錯
簡介
Laravel 的資料庫查詢構建器提供了一個方便、流暢的介面,用於建立和執行資料庫查詢。它可用於執行應用程式中的大多數資料庫操作,並與 Laravel 支援的所有資料庫系統完美協作。
Laravel 查詢構建器使用 PDO 引數繫結來保護您的應用程式免受 SQL 注入攻擊。無需對作為查詢繫結傳遞給查詢構建器的字串進行清理或轉義。
PDO 不支援繫結列名。因此,您永遠不應該允許使用者輸入來指定查詢中引用的列名,包括 "order by" 列。
執行資料庫查詢
從表中檢索所有行
您可以使用 DB 門面提供的 table 方法開始查詢。table 方法返回一個針對給定表的流暢查詢構建器例項,允許您在查詢上鍊接更多約束,最後使用 get 方法檢索查詢結果。
1<?php 2 3namespace App\Http\Controllers; 4 5use Illuminate\Support\Facades\DB; 6use Illuminate\View\View; 7 8class UserController extends Controller 9{10 /**11 * Show a list of all of the application's users.12 */13 public function index(): View14 {15 $users = DB::table('users')->get();16 17 return view('user.index', ['users' => $users]);18 }19}
get 方法返回一個 Illuminate\Support\Collection 例項,其中包含查詢結果,每個結果都是 PHP stdClass 物件的一個例項。您可以透過將列作為物件的屬性來訪問每個列的值。
1use Illuminate\Support\Facades\DB;2 3$users = DB::table('users')->get();4 5foreach ($users as $user) {6 echo $user->name;7}
Laravel 集合提供了多種非常強大的方法來對映和縮減資料。有關 Laravel 集合的更多資訊,請檢視集合文件。
從表中檢索單行/單列
如果您只需要從資料庫表中檢索一行,可以使用 DB 門面的 first 方法。此方法將返回一個 stdClass 物件。
1$user = DB::table('users')->where('name', 'John')->first();2 3return $user->email;
如果您想從資料庫表中檢索一行,但如果未找到匹配行則丟擲 Illuminate\Database\RecordNotFoundException 異常,可以使用 firstOrFail 方法。如果 RecordNotFoundException 未被捕獲,將自動向客戶端傳送 404 HTTP 響應。
1$user = DB::table('users')->where('name', 'John')->firstOrFail();
如果您不需要整行資料,可以使用 value 方法從記錄中提取單個值。此方法將直接返回該列的值。
1$email = DB::table('users')->where('name', 'John')->value('email');
要透過 id 列值檢索單行,請使用 find 方法。
1$user = DB::table('users')->find(3);
檢索列值列表
如果您想檢索一個包含單列值的 Illuminate\Support\Collection 例項,可以使用 pluck 方法。在此示例中,我們將檢索使用者標題的集合。
1use Illuminate\Support\Facades\DB;2 3$titles = DB::table('users')->pluck('title');4 5foreach ($titles as $title) {6 echo $title;7}
您可以透過向 pluck 方法傳遞第二個引數,來指定生成的集合應使用哪一列作為其鍵。
1$titles = DB::table('users')->pluck('title', 'name');2 3foreach ($titles as $name => $title) {4 echo $title;5}
分塊獲取結果
如果您需要處理數千條資料庫記錄,請考慮使用 DB 門面提供的 chunk 方法。該方法一次檢索一小塊結果,並將每一塊結果饋送到閉包中進行處理。例如,讓我們以每次 100 條記錄的分塊方式檢索整個 users 表。
1use Illuminate\Support\Collection;2use Illuminate\Support\Facades\DB;3 4DB::table('users')->orderBy('id')->chunk(100, function (Collection $users) {5 foreach ($users as $user) {6 // ...7 }8});
您可以透過在閉包中返回 false 來停止後續分塊的處理。
1DB::table('users')->orderBy('id')->chunk(100, function (Collection $users) {2 // Process the records...3 4 return false;5});
如果您在分塊處理結果時更新資料庫記錄,分塊結果可能會以意想不到的方式發生變化。如果您計劃在分塊時更新檢索到的記錄,最好改用 chunkById 方法。該方法將根據記錄的主鍵自動對結果進行分頁。
1DB::table('users')->where('active', false)2 ->chunkById(100, function (Collection $users) {3 foreach ($users as $user) {4 DB::table('users')5 ->where('id', $user->id)6 ->update(['active' => true]);7 }8 });
由於 chunkById 和 lazyById 方法會將它們自己的 "where" 條件新增到正在執行的查詢中,因此您通常應該在閉包內邏輯地分組您自己的條件。
1DB::table('users')->where(function ($query) {2 $query->where('credits', 1)->orWhere('credits', 2);3})->chunkById(100, function (Collection $users) {4 foreach ($users as $user) {5 DB::table('users')6 ->where('id', $user->id)7 ->update(['credits' => 3]);8 }9});
在分塊回撥內更新或刪除記錄時,主鍵或外部索引鍵的任何更改都可能影響分塊查詢。這可能會導致某些記錄未被包含在分塊結果中。
流式延遲獲取結果
lazy 方法的工作方式類似於分塊方法,因為它分塊執行查詢。但是,lazy() 方法不是將每一塊傳遞給回撥,而是返回一個 LazyCollection,讓您可以將結果作為單一流進行互動。
1use Illuminate\Support\Facades\DB;2 3DB::table('users')->orderBy('id')->lazy()->each(function (object $user) {4 // ...5});
同樣,如果您計劃在迭代檢索到的記錄時更新它們,最好改用 lazyById 或 lazyByIdDesc 方法。這些方法將根據記錄的主鍵自動對結果進行分頁。
1DB::table('users')->where('active', false)2 ->lazyById()->each(function (object $user) {3 DB::table('users')4 ->where('id', $user->id)5 ->update(['active' => true]);6 });
在迭代期間更新或刪除記錄時,主鍵或外部索引鍵的任何更改都可能影響分塊查詢。這可能會導致某些記錄未被包含在結果中。
聚合函式
查詢構建器還提供了各種用於檢索聚合值的方法,如 count、max、min、avg 和 sum。您可以在構建查詢後呼叫這些方法中的任何一個。
1use Illuminate\Support\Facades\DB;2 3$users = DB::table('users')->count();4 5$price = DB::table('orders')->max('price');
當然,您可以將這些方法與其他子句結合使用,以精細調整聚合值的計算方式。
1$price = DB::table('orders')2 ->where('finalized', 1)3 ->avg('price');
確定記錄是否存在
除了使用 count 方法來確定是否存在符合查詢約束的記錄外,您還可以使用 exists 和 doesntExist 方法。
1if (DB::table('orders')->where('finalized', 1)->exists()) {2 // ...3}4 5if (DB::table('orders')->where('finalized', 1)->doesntExist()) {6 // ...7}
查詢語句 (Select Statements)
指定 Select 子句
您可能並不總是希望從資料庫表中選擇所有列。使用 select 方法,您可以為查詢指定自定義的 "select" 子句。
1use Illuminate\Support\Facades\DB;2 3$users = DB::table('users')4 ->select('name', 'email as user_email')5 ->get();
distinct 方法允許您強制查詢返回不重複的結果。
1$users = DB::table('users')->distinct()->get();
如果您已經擁有一個查詢構建器例項,並希望向其現有的 select 子句中新增列,可以使用 addSelect 方法。
1$query = DB::table('users')->select('name');2 3$users = $query->addSelect('age')->get();
原生表示式
有時您可能需要將任意字串插入到查詢中。要建立原生字串表示式,可以使用 DB 門面提供的 raw 方法。
1$users = DB::table('users')2 ->select(DB::raw('count(*) as user_count, status'))3 ->where('status', '<>', 1)4 ->groupBy('status')5 ->get();
原生語句將作為字串注入到查詢中,因此您應該格外小心,以避免產生 SQL 注入漏洞。
原生方法
除了使用 DB::raw 方法外,您還可以使用以下方法將原生表示式插入到查詢的不同部分。請記住,Laravel 無法保證任何使用原生表示式的查詢都能免受 SQL 注入漏洞的影響。
selectRaw
selectRaw 方法可以代替 addSelect(DB::raw(/* ... */)) 使用。此方法接受一個可選的繫結陣列作為其第二個引數。
1$orders = DB::table('orders')2 ->selectRaw('price * ? as price_with_tax', [1.0825])3 ->get();
whereRaw / orWhereRaw
whereRaw 和 orWhereRaw 方法可用於將原生 "where" 子句注入到查詢中。這些方法接受一個可選的繫結陣列作為其第二個引數。
1$orders = DB::table('orders')2 ->whereRaw('price > IF(state = "TX", ?, 100)', [200])3 ->get();
havingRaw / orHavingRaw
havingRaw 和 orHavingRaw 方法可用於提供原生字串作為 "having" 子句的值。這些方法接受一個可選的繫結陣列作為其第二個引數。
1$orders = DB::table('orders')2 ->select('department', DB::raw('SUM(price) as total_sales'))3 ->groupBy('department')4 ->havingRaw('SUM(price) > ?', [2500])5 ->get();
orderByRaw
orderByRaw 方法可用於提供原生字串作為 "order by" 子句的值。
1$orders = DB::table('orders')2 ->orderByRaw('updated_at - created_at DESC')3 ->get();
groupByRaw
groupByRaw 方法可用於提供原生字串作為 "group by" 子句的值。
1$orders = DB::table('orders')2 ->select('city', 'state')3 ->groupByRaw('city, state')4 ->get();
連線 (Joins)
Inner Join 子句
查詢構建器也可以用於向查詢新增連線子句。要執行基礎的 "inner join",您可以在查詢構建器例項上使用 join 方法。傳遞給 join 方法的第一個引數是您需要連線的表名,而其餘引數指定連線的列約束。您甚至可以在單個查詢中連線多個表。
1use Illuminate\Support\Facades\DB;2 3$users = DB::table('users')4 ->join('contacts', 'users.id', '=', 'contacts.user_id')5 ->join('orders', 'users.id', '=', 'orders.user_id')6 ->select('users.*', 'contacts.phone', 'orders.price')7 ->get();
Left Join / Right Join 子句
如果您想執行 "left join" 或 "right join" 而不是 "inner join",請使用 leftJoin 或 rightJoin 方法。這些方法的簽名與 join 方法相同。
1$users = DB::table('users')2 ->leftJoin('posts', 'users.id', '=', 'posts.user_id')3 ->get();4 5$users = DB::table('users')6 ->rightJoin('posts', 'users.id', '=', 'posts.user_id')7 ->get();
Cross Join 子句
您可以使用 crossJoin 方法執行 "cross join"(交叉連線)。交叉連線在第一張表和連線表之間生成笛卡爾積。
1$sizes = DB::table('sizes')2 ->crossJoin('colors')3 ->get();
高階 Join 子句
您還可以指定更高階的連線子句。首先,將一個閉包作為第二個引數傳遞給 join 方法。該閉包將接收一個 Illuminate\Database\Query\JoinClause 例項,允許您指定 "join" 子句的約束。
1DB::table('users')2 ->join('contacts', function (JoinClause $join) {3 $join->on('users.id', '=', 'contacts.user_id')->orOn(/* ... */);4 })5 ->get();
如果您想在連線上使用 "where" 子句,可以使用 JoinClause 例項提供的 where 和 orWhere 方法。這些方法不是比較兩個列,而是將列與值進行比較。
1DB::table('users')2 ->join('contacts', function (JoinClause $join) {3 $join->on('users.id', '=', 'contacts.user_id')4 ->where('contacts.user_id', '>', 5);5 })6 ->get();
子查詢 Joins
您可以使用 joinSub、leftJoinSub 和 rightJoinSub 方法將查詢連線到子查詢。這些方法中的每一個都接收三個引數:子查詢、其表別名以及一個定義關聯列的閉包。在此示例中,我們將檢索使用者集合,其中每個使用者記錄還包含使用者最近釋出的部落格文章的 created_at 時間戳。
1$latestPosts = DB::table('posts')2 ->select('user_id', DB::raw('MAX(created_at) as last_post_created_at'))3 ->where('is_published', true)4 ->groupBy('user_id');5 6$users = DB::table('users')7 ->joinSub($latestPosts, 'latest_posts', function (JoinClause $join) {8 $join->on('users.id', '=', 'latest_posts.user_id');9 })->get();
Lateral Joins
Lateral joins 目前受 PostgreSQL、MySQL >= 8.0.14 和 SQL Server 支援。
您可以使用 joinLateral 和 leftJoinLateral 方法對子查詢執行 "lateral join"。這些方法中的每一個都接收兩個引數:子查詢及其表別名。連線條件應在給定子查詢的 where 子句中指定。Lateral joins 為每一行進行計算,並且可以引用子查詢外部的列。
在此示例中,我們將檢索使用者集合以及使用者最近的三篇部落格文章。每個使用者在結果集中最多產生三行:每行對應其最近的一篇部落格文章。連線條件在子查詢中使用 whereColumn 子句指定,引用當前使用者行。
1$latestPosts = DB::table('posts')2 ->select('id as post_id', 'title as post_title', 'created_at as post_created_at')3 ->whereColumn('user_id', 'users.id')4 ->orderBy('created_at', 'desc')5 ->limit(3);6 7$users = DB::table('users')8 ->joinLateral($latestPosts, 'latest_posts')9 ->get();
聯合查詢 (Unions)
查詢構建器還提供了一種方便的方法來將兩個或多個查詢 "union" 在一起。例如,您可以建立一個初始查詢,並使用 union 方法將其與其他查詢聯合起來。
1use Illuminate\Support\Facades\DB;2 3$usersWithoutFirstName = DB::table('users')4 ->whereNull('first_name');5 6$users = DB::table('users')7 ->whereNull('last_name')8 ->union($usersWithoutFirstName)9 ->get();
除了 union 方法外,查詢構建器還提供了 unionAll 方法。使用 unionAll 方法合併的查詢不會刪除重複結果。unionAll 方法的方法簽名與 union 方法相同。
基礎 Where 子句
Where 子句
您可以使用查詢構建器的 where 方法將 "where" 子句新增到查詢中。對 where 方法最基本的呼叫需要三個引數。第一個引數是列名。第二個引數是運算子,可以是資料庫支援的任何運算子。第三個引數是與列值進行比較的值。
例如,以下查詢檢索 votes 列值等於 100 且 age 列值大於 35 的使用者。
1$users = DB::table('users')2 ->where('votes', '=', 100)3 ->where('age', '>', 35)4 ->get();
為方便起見,如果您想驗證某一列 = 給定值,可以將該值作為第二個引數傳遞給 where 方法。Laravel 將假定您希望使用 = 運算子。
1$users = DB::table('users')->where('votes', 100)->get();
您還可以向 where 方法提供關聯陣列,以快速查詢多個列。
1$users = DB::table('users')->where([2 'first_name' => 'Jane',3 'last_name' => 'Doe',4])->get();
如前所述,您可以使用您的資料庫系統支援的任何運算子。
1$users = DB::table('users') 2 ->where('votes', '>=', 100) 3 ->get(); 4 5$users = DB::table('users') 6 ->where('votes', '<>', 100) 7 ->get(); 8 9$users = DB::table('users')10 ->where('name', 'like', 'T%')11 ->get();
您還可以將條件陣列傳遞給 where 函式。陣列的每個元素都應是一個數組,其中包含通常傳遞給 where 方法的三個引數。
1$users = DB::table('users')->where([2 ['status', '=', '1'],3 ['subscribed', '<>', '1'],4])->get();
PDO 不支援繫結列名。因此,您永遠不應該允許使用者輸入來指定查詢中引用的列名,包括 "order by" 列。
MySQL 和 MariaDB 會在字串與數字比較中自動將字串型別轉換為整數。在此過程中,非數字字串會被轉換為 0,這可能導致意想不到的結果。例如,如果您的表有一個值為 aaa 的 secret 列,並且您執行 User::where('secret', 0),該行將被返回。為避免這種情況,請確保在查詢中使用值之前,所有值都已強制轉換為其適當的型別。
Or Where 子句
在連結呼叫查詢構建器的 where 方法時,"where" 子句將使用 and 運算子連線在一起。但是,您可以使用 orWhere 方法使用 or 運算子將子句連線到查詢。orWhere 方法接受與 where 方法相同的引數。
1$users = DB::table('users')2 ->where('votes', '>', 100)3 ->orWhere('name', 'John')4 ->get();
如果您需要將 "or" 條件分組在括號內,可以將閉包作為第一個引數傳遞給 orWhere 方法。
1use Illuminate\Database\Query\Builder;2 3$users = DB::table('users')4 ->where('votes', '>', 100)5 ->orWhere(function (Builder $query) {6 $query->where('name', 'Abigail')7 ->where('votes', '>', 50);8 })9 ->get();
上面的示例將生成以下 SQL:
1select * from users where votes > 100 or (name = 'Abigail' and votes > 50)
您應該始終對 orWhere 呼叫進行分組,以避免在應用全域性作用域時出現意外行為。
Where Not 子句
whereNot 和 orWhereNot 方法可用於否定給定的查詢約束組。例如,以下查詢排除了清倉商品或價格低於 10 的商品。
1$products = DB::table('products')2 ->whereNot(function (Builder $query) {3 $query->where('clearance', true)4 ->orWhere('price', '<', 10);5 })6 ->get();
Where Any / All / None 子句
有時您可能需要將相同的查詢約束應用於多個列。例如,您可能希望檢索任何給定列列表中 LIKE 給定值的所有記錄。您可以使用 whereAny 方法實現此目的。
1$users = DB::table('users')2 ->where('active', true)3 ->whereAny([4 'name',5 'email',6 'phone',7 ], 'like', 'Example%')8 ->get();
上面的查詢將導致以下 SQL:
1SELECT *2FROM users3WHERE active = true AND (4 name LIKE 'Example%' OR5 email LIKE 'Example%' OR6 phone LIKE 'Example%'7)
同樣,whereAll 方法可用於檢索所有給定列都匹配給定約束的記錄。
1$posts = DB::table('posts')2 ->where('published', true)3 ->whereAll([4 'title',5 'content',6 ], 'like', '%Laravel%')7 ->get();
上面的查詢將導致以下 SQL:
1SELECT *2FROM posts3WHERE published = true AND (4 title LIKE '%Laravel%' AND5 content LIKE '%Laravel%'6)
whereNone 方法可用於檢索沒有任何給定列匹配給定約束的記錄。
1$albums = DB::table('albums')2 ->where('published', true)3 ->whereNone([4 'title',5 'lyrics',6 'tags',7 ], 'like', '%explicit%')8 ->get();
上面的查詢將導致以下 SQL:
1SELECT *2FROM albums3WHERE published = true AND NOT (4 title LIKE '%explicit%' OR5 lyrics LIKE '%explicit%' OR6 tags LIKE '%explicit%'7)
JSON Where 子句
Laravel 還支援在提供 JSON 列型別支援的資料庫上查詢 JSON 列型別。目前,這包括 MariaDB 10.3+、MySQL 8.0+、PostgreSQL 12.0+、SQL Server 2017+ 和 SQLite 3.39.0+。要查詢 JSON 列,請使用 -> 運算子。
1$users = DB::table('users')2 ->where('preferences->dining->meal', 'salad')3 ->get();4 5$users = DB::table('users')6 ->whereIn('preferences->dining->meal', ['pasta', 'salad', 'sandwiches'])7 ->get();
您可以使用 whereJsonContains 和 whereJsonDoesntContain 方法來查詢 JSON 陣列。
1$users = DB::table('users')2 ->whereJsonContains('options->languages', 'en')3 ->get();4 5$users = DB::table('users')6 ->whereJsonDoesntContain('options->languages', 'en')7 ->get();
如果您的應用程式使用 MariaDB、MySQL 或 PostgreSQL 資料庫,您可以將值陣列傳遞給 whereJsonContains 和 whereJsonDoesntContain 方法。
1$users = DB::table('users')2 ->whereJsonContains('options->languages', ['en', 'de'])3 ->get();4 5$users = DB::table('users')6 ->whereJsonDoesntContain('options->languages', ['en', 'de'])7 ->get();
此外,您可以使用 whereJsonContainsKey 或 whereJsonDoesntContainKey 方法來檢索包含或不包含 JSON 鍵的結果。
1$users = DB::table('users')2 ->whereJsonContainsKey('preferences->dietary_requirements')3 ->get();4 5$users = DB::table('users')6 ->whereJsonDoesntContainKey('preferences->dietary_requirements')7 ->get();
最後,您可以使用 whereJsonLength 方法根據長度查詢 JSON 陣列。
1$users = DB::table('users')2 ->whereJsonLength('options->languages', 0)3 ->get();4 5$users = DB::table('users')6 ->whereJsonLength('options->languages', '>', 1)7 ->get();
附加 Where 子句
whereLike / orWhereLike / whereNotLike / orWhereNotLike
whereLike 方法允許您向查詢新增 "LIKE" 子句進行模式匹配。這些方法提供了一種資料庫無關的方式來執行字串匹配查詢,並能夠切換大小寫敏感性。預設情況下,字串匹配是不區分大小寫的。
1$users = DB::table('users')2 ->whereLike('name', '%John%')3 ->get();
您可以透過 caseSensitive 引數啟用區分大小寫的搜尋。
1$users = DB::table('users')2 ->whereLike('name', '%John%', caseSensitive: true)3 ->get();
orWhereLike 方法允許您新增帶有 LIKE 條件的 "or" 子句。
1$users = DB::table('users')2 ->where('votes', '>', 100)3 ->orWhereLike('name', '%John%')4 ->get();
whereNotLike 方法允許您向查詢新增 "NOT LIKE" 子句。
1$users = DB::table('users')2 ->whereNotLike('name', '%John%')3 ->get();
同樣,您可以使用 orWhereNotLike 新增帶有 NOT LIKE 條件的 "or" 子句。
1$users = DB::table('users')2 ->where('votes', '>', 100)3 ->orWhereNotLike('name', '%John%')4 ->get();
SQL Server 目前不支援 whereLike 的大小寫敏感搜尋選項。
whereIn / whereNotIn / orWhereIn / orWhereNotIn
whereIn 方法驗證給定列的值是否包含在給定陣列中。
1$users = DB::table('users')2 ->whereIn('id', [1, 2, 3])3 ->get();
whereNotIn 方法驗證給定列的值是否不包含在給定陣列中。
1$users = DB::table('users')2 ->whereNotIn('id', [1, 2, 3])3 ->get();
您還可以將查詢物件作為 whereIn 方法的第二個引數提供。
1$activeUsers = DB::table('users')->select('id')->where('is_active', 1);2 3$comments = DB::table('comments')4 ->whereIn('user_id', $activeUsers)5 ->get();
上面的示例將生成以下 SQL:
1select * from comments where user_id in (2 select id3 from users4 where is_active = 15)
如果您正在向查詢新增大量的整數繫結陣列,可以使用 whereIntegerInRaw 或 whereIntegerNotInRaw 方法,以大大減少記憶體使用量。
whereBetween / orWhereBetween
whereBetween 方法驗證列的值是否在兩個值之間。
1$users = DB::table('users')2 ->whereBetween('votes', [1, 100])3 ->get();
whereNotBetween / orWhereNotBetween
whereNotBetween 方法驗證列的值是否在兩個值之外。
1$users = DB::table('users')2 ->whereNotBetween('votes', [1, 100])3 ->get();
whereBetweenColumns / whereNotBetweenColumns / orWhereBetweenColumns / orWhereNotBetweenColumns
whereBetweenColumns 方法驗證列的值是否在同一錶行中兩列的兩個值之間。
1$patients = DB::table('patients')2 ->whereBetweenColumns('weight', ['minimum_allowed_weight', 'maximum_allowed_weight'])3 ->get();
whereNotBetweenColumns 方法驗證列的值是否在同一錶行中兩列的兩個值之外。
1$patients = DB::table('patients')2 ->whereNotBetweenColumns('weight', ['minimum_allowed_weight', 'maximum_allowed_weight'])3 ->get();
whereValueBetween / whereValueNotBetween / orWhereValueBetween / orWhereValueNotBetween
whereValueBetween 方法驗證給定值是否在同一錶行中兩列相同型別的兩個值之間。
1$products = DB::table('products')2 ->whereValueBetween(100, ['min_price', 'max_price'])3 ->get();
whereValueNotBetween 方法驗證一個值是否在同一錶行中兩列的兩個值之外。
1$products = DB::table('products')2 ->whereValueNotBetween(100, ['min_price', 'max_price'])3 ->get();
whereNull / whereNotNull / orWhereNull / orWhereNotNull
whereNull 方法驗證給定列的值是否為 NULL。
1$users = DB::table('users')2 ->whereNull('updated_at')3 ->get();
whereNotNull 方法驗證列的值是否不為 NULL。
1$users = DB::table('users')2 ->whereNotNull('updated_at')3 ->get();
whereDate / whereMonth / whereDay / whereYear / whereTime
whereDate 方法可用於將列的值與日期進行比較。
1$users = DB::table('users')2 ->whereDate('created_at', '2016-12-31')3 ->get();
whereMonth 方法可用於將列的值與特定月份進行比較。
1$users = DB::table('users')2 ->whereMonth('created_at', '12')3 ->get();
whereDay 方法可用於將列的值與特定日期進行比較。
1$users = DB::table('users')2 ->whereDay('created_at', '31')3 ->get();
whereYear 方法可用於將列的值與特定年份進行比較。
1$users = DB::table('users')2 ->whereYear('created_at', '2016')3 ->get();
whereTime 方法可用於將列的值與特定時間進行比較。
1$users = DB::table('users')2 ->whereTime('created_at', '=', '11:20:45')3 ->get();
wherePast / whereFuture / whereToday / whereBeforeToday / whereAfterToday
wherePast 和 whereFuture 方法可用於確定列的值是在過去還是未來。
1$invoices = DB::table('invoices')2 ->wherePast('due_at')3 ->get();4 5$invoices = DB::table('invoices')6 ->whereFuture('due_at')7 ->get();
whereNowOrPast 和 whereNowOrFuture 方法可用於確定列的值是在過去還是未來(包含當前日期和時間)。
1$invoices = DB::table('invoices')2 ->whereNowOrPast('due_at')3 ->get();4 5$invoices = DB::table('invoices')6 ->whereNowOrFuture('due_at')7 ->get();
whereToday、whereBeforeToday 和 whereAfterToday 方法分別可用於確定列的值是否為今天、今天之前或今天之後。
1$invoices = DB::table('invoices') 2 ->whereToday('due_at') 3 ->get(); 4 5$invoices = DB::table('invoices') 6 ->whereBeforeToday('due_at') 7 ->get(); 8 9$invoices = DB::table('invoices')10 ->whereAfterToday('due_at')11 ->get();
同樣,whereTodayOrBefore 和 whereTodayOrAfter 方法可用於確定列的值是否在今天之前或今天之後(包含今天日期)。
1$invoices = DB::table('invoices')2 ->whereTodayOrBefore('due_at')3 ->get();4 5$invoices = DB::table('invoices')6 ->whereTodayOrAfter('due_at')7 ->get();
whereColumn / orWhereColumn
whereColumn 方法可用於驗證兩列是否相等。
1$users = DB::table('users')2 ->whereColumn('first_name', 'last_name')3 ->get();
您還可以將比較運算子傳遞給 whereColumn 方法。
1$users = DB::table('users')2 ->whereColumn('updated_at', '>', 'created_at')3 ->get();
您還可以將列比較陣列傳遞給 whereColumn 方法。這些條件將使用 and 運算子連線。
1$users = DB::table('users')2 ->whereColumn([3 ['first_name', '=', 'last_name'],4 ['updated_at', '>', 'created_at'],5 ])->get();
邏輯分組
有時您可能需要將多個 "where" 子句分組在括號內,以實現查詢所需的邏輯分組。實際上,您通常應該始終在括號中對 orWhere 方法的呼叫進行分組,以避免意外的查詢行為。要實現這一點,您可以將閉包傳遞給 where 方法。
1$users = DB::table('users')2 ->where('name', '=', 'John')3 ->where(function (Builder $query) {4 $query->where('votes', '>', 100)5 ->orWhere('title', '=', 'Admin');6 })7 ->get();
如您所見,將閉包傳遞給 where 方法指示查詢構建器開始一個約束組。該閉包將接收一個查詢構建器例項,您可以使用該例項設定應包含在括號組中的約束。上面的示例將生成以下 SQL:
1select * from users where name = 'John' and (votes > 100 or title = 'Admin')
您應該始終對 orWhere 呼叫進行分組,以避免在應用全域性作用域時出現意外行為。
高階 Where 子句
Where Exists 子句
whereExists 方法允許您編寫 "where exists" SQL 子句。whereExists 方法接受一個閉包,該閉包將接收一個查詢構建器例項,允許您定義應放置在 "exists" 子句內的查詢。
1$users = DB::table('users')2 ->whereExists(function (Builder $query) {3 $query->select(DB::raw(1))4 ->from('orders')5 ->whereColumn('orders.user_id', 'users.id');6 })7 ->get();
或者,您可以向 whereExists 方法提供查詢物件,而不是閉包。
1$orders = DB::table('orders')2 ->select(DB::raw(1))3 ->whereColumn('orders.user_id', 'users.id');4 5$users = DB::table('users')6 ->whereExists($orders)7 ->get();
以上兩個示例都將生成以下 SQL:
1select * from users2where exists (3 select 14 from orders5 where orders.user_id = users.id6)
子查詢 Where 子句
有時您可能需要構造一個將子查詢結果與給定值進行比較的 "where" 子句。您可以透過將閉包和值傳遞給 where 方法來實現。例如,以下查詢將檢索所有擁有給定型別最近 "membership" 的使用者:
1use App\Models\User; 2use Illuminate\Database\Query\Builder; 3 4$users = User::where(function (Builder $query) { 5 $query->select('type') 6 ->from('membership') 7 ->whereColumn('membership.user_id', 'users.id') 8 ->orderByDesc('membership.start_date') 9 ->limit(1);10}, 'Pro')->get();
或者,您可能需要構造一個將列與子查詢結果進行比較的 "where" 子句。您可以透過將列、運算子和閉包傳遞給 where 方法來實現。例如,以下查詢將檢索所有金額小於平均值的收入記錄:
1use App\Models\Income;2use Illuminate\Database\Query\Builder;3 4$incomes = Income::where('amount', '<', function (Builder $query) {5 $query->selectRaw('avg(i.amount)')->from('incomes as i');6})->get();
全文搜尋 Where 子句
全文搜尋 Where 子句目前受 MariaDB、MySQL 和 PostgreSQL 支援。
whereFullText 和 orWhereFullText 方法可用於為具有全文索引的列向查詢新增全文 "where" 子句。這些方法將被 Laravel 轉換為底層資料庫系統所需的適當 SQL。例如,將為使用 MariaDB 或 MySQL 的應用程式生成 MATCH AGAINST 子句。
1$users = DB::table('users')2 ->whereFullText('bio', 'web developer')3 ->get();
向量相似度子句
向量相似度子句目前僅在使用 pgvector 擴充套件的 PostgreSQL 連線上受支援。有關定義向量列和索引的資訊,請諮詢遷移文件。
whereVectorSimilarTo 方法根據給定向量的餘弦相似度過濾結果,並按相關性對結果進行排序。minSimilarity 閾值應為 0.0 到 1.0 之間的值,其中 1.0 表示完全相同。
1$documents = DB::table('documents')2 ->whereVectorSimilarTo('embedding', $queryEmbedding, minSimilarity: 0.4)3 ->limit(10)4 ->get();
當純字串作為向量引數給出時,Laravel 將自動使用 Laravel AI SDK 為其生成嵌入。
1$documents = DB::table('documents')2 ->whereVectorSimilarTo('embedding', 'Best wineries in Napa Valley')3 ->limit(10)4 ->get();
預設情況下,whereVectorSimilarTo 也會按距離對結果排序(最相似的優先)。您可以透過將 false 作為 order 引數傳遞來停用此排序。
1$documents = DB::table('documents')2 ->whereVectorSimilarTo('embedding', $queryEmbedding, minSimilarity: 0.4, order: false)3 ->orderBy('created_at', 'desc')4 ->limit(10)5 ->get();
如果您需要更多控制,可以獨立使用 selectVectorDistance、whereVectorDistanceLessThan 和 orderByVectorDistance 方法。
1$documents = DB::table('documents')2 ->select('*')3 ->selectVectorDistance('embedding', $queryEmbedding, as: 'distance')4 ->whereVectorDistanceLessThan('embedding', $queryEmbedding, maxDistance: 0.3)5 ->orderByVectorDistance('embedding', $queryEmbedding)6 ->limit(10)7 ->get();
使用 PostgreSQL 時,必須先載入 pgvector 擴充套件,然後才能建立 vector 列。
1Schema::ensureVectorExtensionExists();
排序、分組、限制與偏移
排序
orderBy 方法
orderBy 方法允許您按給定列對查詢結果進行排序。orderBy 方法接受的第一個引數應為您希望排序的列,而第二個引數決定排序方向,可以是 asc 或 desc。
1$users = DB::table('users')2 ->orderBy('name', 'desc')3 ->get();
要按多列排序,只需根據需要多次呼叫 orderBy 即可。
1$users = DB::table('users')2 ->orderBy('name', 'desc')3 ->orderBy('email', 'asc')4 ->get();
排序方向是可選的,預設為升序。如果您想按降序排序,可以為 orderBy 方法指定第二個引數,或者直接使用 orderByDesc。
1$users = DB::table('users')2 ->orderByDesc('verified_at')3 ->get();
最後,使用 -> 運算子,可以按 JSON 列中的值對結果進行排序。
1$corporations = DB::table('corporations')2 ->where('country', 'US')3 ->orderBy('location->state')4 ->get();
latest 和 oldest 方法
latest 和 oldest 方法允許您輕鬆地按日期對結果進行排序。預設情況下,結果將按表的 created_at 列進行排序。或者,您可以傳遞您希望排序的列名。
1$user = DB::table('users')2 ->latest()3 ->first();
隨機排序
inRandomOrder 方法可用於隨機對查詢結果進行排序。例如,您可以使用此方法獲取一個隨機使用者。
1$randomUser = DB::table('users')2 ->inRandomOrder()3 ->first();
移除現有排序
reorder 方法會移除之前已應用於查詢的所有 "order by" 子句。
1$query = DB::table('users')->orderBy('name');2 3$unorderedUsers = $query->reorder()->get();
您可以在呼叫 reorder 方法時傳遞列和方向,以移除所有現有的 "order by" 子句並對查詢應用全新的排序。
1$query = DB::table('users')->orderBy('name');2 3$usersOrderedByEmail = $query->reorder('email', 'desc')->get();
為方便起見,您可以使用 reorderDesc 方法以降序對查詢結果重新排序。
1$query = DB::table('users')->orderBy('name');2 3$usersOrderedByEmail = $query->reorderDesc('email')->get();
分組
groupBy 和 having 方法
正如您所預料的,groupBy 和 having 方法可用於對查詢結果進行分組。having 方法的簽名類似於 where 方法。
1$users = DB::table('users')2 ->groupBy('account_id')3 ->having('account_id', '>', 100)4 ->get();
您可以使用 havingBetween 方法來過濾給定範圍內的結果。
1$report = DB::table('orders')2 ->selectRaw('count(id) as number_of_orders, customer_id')3 ->groupBy('customer_id')4 ->havingBetween('number_of_orders', [5, 15])5 ->get();
您可以將多個引數傳遞給 groupBy 方法以按多列分組。
1$users = DB::table('users')2 ->groupBy('first_name', 'status')3 ->having('account_id', '>', 100)4 ->get();
要構建更高階的 having 語句,請參閱 havingRaw 方法。
限制與偏移
您可以使用 limit 和 offset 方法來限制從查詢返回的結果數量,或跳過查詢中的給定數量結果。
1$users = DB::table('users')2 ->offset(10)3 ->limit(5)4 ->get();
條件子句
有時您可能希望根據另一個條件將特定的查詢子句應用於查詢。例如,您可能只想在傳入的 HTTP 請求中存在給定的輸入值時才應用 where 語句。您可以使用 when 方法實現此目的。
1$role = $request->input('role');2 3$users = DB::table('users')4 ->when($role, function (Builder $query, string $role) {5 $query->where('role_id', $role);6 })7 ->get();
when 方法僅在第一個引數為 true 時執行給定的閉包。如果第一個引數為 false,則不會執行該閉包。因此,在上面的示例中,提供給 when 方法的閉包僅在 role 欄位出現在傳入請求中且計算結果為 true 時才會被呼叫。
您可以將另一個閉包作為第三個引數傳遞給 when 方法。此閉包僅在第一個引數計算結果為 false 時執行。為了說明如何使用此功能,我們將使用它來配置查詢的預設排序。
1$sortByVotes = $request->boolean('sort_by_votes');2 3$users = DB::table('users')4 ->when($sortByVotes, function (Builder $query, bool $sortByVotes) {5 $query->orderBy('votes');6 }, function (Builder $query) {7 $query->orderBy('name');8 })9 ->get();
插入語句
查詢構建器還提供了一個 insert 方法,可用於向資料庫表中插入記錄。insert 方法接受列名和值的陣列。
1DB::table('users')->insert([3 'votes' => 04]);
您可以透過傳遞陣列的陣列來一次插入多條記錄。每個陣列代表應插入表中的一條記錄。
1DB::table('users')->insert([4]);
insertOrIgnore 方法將在向資料庫插入記錄時忽略錯誤。使用此方法時,請注意重複記錄錯誤將被忽略,並且根據資料庫引擎的不同,其他型別的錯誤也可能被忽略。例如,insertOrIgnore 將繞過 MySQL 的嚴格模式。
1DB::table('users')->insertOrIgnore([4]);
insertUsing 方法將在使用子查詢確定應插入的資料的同時,向表中插入新記錄。
1DB::table('pruned_users')->insertUsing([2 'id', 'name', 'email', 'email_verified_at'3], DB::table('users')->select(4 'id', 'name', 'email', 'email_verified_at'5)->where('updated_at', '<=', now()->minus(months: 1)));
自動遞增 ID
如果表具有自動遞增 ID,請使用 insertGetId 方法插入記錄並檢索該 ID。
1$id = DB::table('users')->insertGetId(3);
使用 PostgreSQL 時,insertGetId 方法期望自動遞增列被命名為 id。如果您想從不同的 "sequence" 中檢索 ID,可以將列名作為第二個引數傳遞給 insertGetId 方法。
Upsert (更新或插入)
upsert 方法將插入不存在的記錄,並使用您指定的新值更新已存在的記錄。該方法的第一個引數由要插入或更新的值組成,第二個引數列出了在關聯表中唯一標識記錄的列。該方法的第三個(也是最後一個)引數是當資料庫中已存在匹配記錄時應更新的列陣列。
1DB::table('flights')->upsert(2 [3 ['departure' => 'Oakland', 'destination' => 'San Diego', 'price' => 99],4 ['departure' => 'Chicago', 'destination' => 'New York', 'price' => 150]5 ],6 ['departure', 'destination'],7 ['price']8);
在上面的示例中,Laravel 將嘗試插入兩條記錄。如果已存在具有相同 departure 和 destination 列值的記錄,Laravel 將更新該記錄的 price 列。
除 SQL Server 外,所有資料庫都要求 upsert 方法第二個引數中的列具有 "primary" 或 "unique" 索引。此外,MariaDB 和 MySQL 資料庫驅動程式會忽略 upsert 方法的第二個引數,並始終使用表的 "primary" 和 "unique" 索引來檢測現有記錄。
更新語句
除了向資料庫插入記錄外,查詢構建器還可以使用 update 方法更新現有記錄。與 insert 方法一樣,update 方法接受列和值對的陣列,指示要更新的列。update 方法返回受影響的行數。您可以使用 where 子句約束 update 查詢。
1$affected = DB::table('users')2 ->where('id', 1)3 ->update(['votes' => 1]);
更新或插入
有時您可能希望更新資料庫中的現有記錄,如果不存在匹配記錄,則建立它。在這種情況下,可以使用 updateOrInsert 方法。updateOrInsert 方法接受兩個引數:用於查詢記錄的條件陣列,以及指示要更新的列和值對的陣列。
updateOrInsert 方法將嘗試使用第一個引數的列和值對來定位匹配的資料庫記錄。如果記錄存在,它將使用第二個引數中的值進行更新。如果找不到記錄,將插入一條包含兩個引數合併屬性的新記錄。
1DB::table('users')2 ->updateOrInsert(4 ['votes' => '2']5 );
您可以向 updateOrInsert 方法提供閉包,以根據是否存在匹配記錄來自定義插入或更新到資料庫中的屬性。
1DB::table('users')->updateOrInsert( 2 ['user_id' => $user_id], 3 fn ($exists) => $exists ? [ 4 'name' => $data['name'], 5 'email' => $data['email'], 6 ] : [ 7 'name' => $data['name'], 8 'email' => $data['email'], 9 'marketable' => true,10 ],11);
更新 JSON 列
更新 JSON 列時,應使用 -> 語法來更新 JSON 物件中的相應鍵。此操作在 MariaDB 10.3+、MySQL 5.7+ 和 PostgreSQL 9.5+ 上受支援。
1$affected = DB::table('users')2 ->where('id', 1)3 ->update(['options->enabled' => true]);
遞增與遞減
查詢構建器還提供了用於遞增或遞減給定列值的便捷方法。這兩個方法至少接受一個引數:要修改的列。可以提供第二個引數來指定列應遞增或遞減的量。
1DB::table('users')->increment('votes');2 3DB::table('users')->increment('votes', 5);4 5DB::table('users')->decrement('votes');6 7DB::table('users')->decrement('votes', 5);
如果需要,您還可以在遞增或遞減操作期間指定要更新的其他列。
1DB::table('users')->increment('votes', 1, ['name' => 'John']);
此外,您可以使用 incrementEach 和 decrementEach 方法同時遞增或遞減多個列。
1DB::table('users')->incrementEach([2 'votes' => 5,3 'balance' => 100,4]);
刪除語句
查詢構建器的 delete 方法可用於從表中刪除記錄。delete 方法返回受影響的行數。您可以在呼叫 delete 方法之前新增 "where" 子句來約束 delete 語句。
1$deleted = DB::table('users')->delete();2 3$deleted = DB::table('users')->where('votes', '>', 100)->delete();
悲觀鎖
查詢構建器還包含一些函式,可幫助您在執行 select 語句時實現 "悲觀鎖"。要執行帶有 "shared lock"(共享鎖)的語句,您可以呼叫 sharedLock 方法。共享鎖可防止選定行在您的事務提交之前被修改。
1DB::table('users')2 ->where('votes', '>', 100)3 ->sharedLock()4 ->get();
或者,您可以使用 lockForUpdate 方法。"for update" 鎖可防止選定記錄被修改或被其他共享鎖選中。
1DB::table('users')2 ->where('votes', '>', 100)3 ->lockForUpdate()4 ->get();
雖然不是必須的,但建議在事務中包裝悲觀鎖。這確保檢索到的資料在整個操作完成之前在資料庫中保持不變。如果發生故障,事務將回滾所有更改並自動釋放鎖。
1DB::transaction(function () { 2 $sender = DB::table('users') 3 ->lockForUpdate() 4 ->find(1); 5 6 $receiver = DB::table('users') 7 ->lockForUpdate() 8 ->find(2); 9 10 if ($sender->balance < 100) {11 throw new RuntimeException('Balance too low.');12 }13 14 DB::table('users')15 ->where('id', $sender->id)16 ->update([17 'balance' => $sender->balance - 10018 ]);19 20 DB::table('users')21 ->where('id', $receiver->id)22 ->update([23 'balance' => $receiver->balance + 10024 ]);25});
可複用的查詢元件
如果您在整個應用程式中重複查詢邏輯,可以使用查詢構建器的 tap 和 pipe 方法將邏輯提取到可重用的物件中。想象一下您在應用程式中有這兩個不同的查詢:
1use Illuminate\Database\Query\Builder; 2use Illuminate\Support\Facades\DB; 3 4$destination = $request->query('destination'); 5 6DB::table('flights') 7 ->when($destination, function (Builder $query, string $destination) { 8 $query->where('destination', $destination); 9 })10 ->orderByDesc('price')11 ->get();12 13// ...14 15$destination = $request->query('destination');16 17DB::table('flights')18 ->when($destination, function (Builder $query, string $destination) {19 $query->where('destination', $destination);20 })21 ->where('user', $request->user()->id)22 ->orderBy('destination')23 ->get();
您可能希望將查詢之間通用的目標過濾提取到可重用的物件中:
1<?php 2 3namespace App\Scopes; 4 5use Illuminate\Database\Query\Builder; 6 7class DestinationFilter 8{ 9 public function __construct(10 private ?string $destination,11 ) {12 //13 }14 15 public function __invoke(Builder $query): void16 {17 $query->when($this->destination, function (Builder $query) {18 $query->where('destination', $this->destination);19 });20 }21}
然後,您可以使用查詢構建器的 tap 方法將物件的邏輯應用於查詢:
1use App\Scopes\DestinationFilter; 2use Illuminate\Database\Query\Builder; 3use Illuminate\Support\Facades\DB; 4 5DB::table('flights') 6 ->when($destination, function (Builder $query, string $destination) { 7 $query->where('destination', $destination); 8 }) 9 ->tap(new DestinationFilter($destination)) 10 ->orderByDesc('price')11 ->get();12 13// ...14 15DB::table('flights')16 ->when($destination, function (Builder $query, string $destination) { 17 $query->where('destination', $destination); 18 }) 19 ->tap(new DestinationFilter($destination)) 20 ->where('user', $request->user()->id)21 ->orderBy('destination')22 ->get();
查詢管道 (Query Pipes)
tap 方法將始終返回查詢構建器。如果您想提取一個執行查詢並返回其他值的物件,則可以使用 pipe 方法。
考慮以下查詢物件,其中包含在整個應用程式中使用的共享分頁邏輯。與將查詢條件應用於查詢的 DestinationFilter 不同,Paginate 物件執行查詢並返回分頁器例項:
1<?php 2 3namespace App\Scopes; 4 5use Illuminate\Contracts\Pagination\LengthAwarePaginator; 6use Illuminate\Database\Query\Builder; 7 8class Paginate 9{10 public function __construct(11 private string $sortBy = 'timestamp',12 private string $sortDirection = 'desc',13 private int $perPage = 25,14 ) {15 //16 }17 18 public function __invoke(Builder $query): LengthAwarePaginator19 {20 return $query->orderBy($this->sortBy, $this->sortDirection)21 ->paginate($this->perPage, pageName: 'p');22 }23}
使用查詢構建器的 pipe 方法,我們可以利用此物件來應用我們的共享分頁邏輯:
1$flights = DB::table('flights')2 ->tap(new DestinationFilter($destination))3 ->pipe(new Paginate);
除錯
您可以在構建查詢時使用 dd 和 dump 方法來輸出當前查詢繫結和 SQL。dd 方法將顯示除錯資訊,然後停止執行請求。dump 方法將顯示除錯資訊,但允許請求繼續執行。
1DB::table('users')->where('votes', '>', 100)->dd();2 3DB::table('users')->where('votes', '>', 100)->dump();
dumpRawSql 和 ddRawSql 方法可以在查詢上呼叫,以輸出已正確替換所有引數繫結的查詢 SQL。
1DB::table('users')->where('votes', '>', 100)->dumpRawSql();2 3DB::table('users')->where('votes', '>', 100)->ddRawSql();