laravel 控制器類DB類操作


從數據表中取得所有的數據列

$users = DB::table('users')->get(); foreach ($users as $user) { var_dump($user->name); } 

從數據表中分塊查找數據列

DB::table('users')->chunk(100, function($users) { foreach ($users as $user) {  // } }); 

通過在 閉包 中返回 false 來停止處理接下來的數據列:

DB::table('users')->chunk(100, function($users) {  // return false; }); 

從數據表中取得單一數據列

$user = DB::table('users')->where('name', 'John')->first(); var_dump($user->name); 

從數據表中取得單一數據列的單一字段

$name = DB::table('users')->where('name', 'John')->pluck('name'); 

取得單一字段值的列表

$roles = DB::table('roles')->lists('title'); 

這個方法將會返回數據表 role 的 title 字段值的數組。你也可以通過下面的方法,為返回的數組指定自定義鍵值。

$roles = DB::table('roles')->lists('title', 'name'); 

指定查詢子句 (Select Clause)

$users = DB::table('users')->select('name', 'email')->get(); $users = DB::table('users')->distinct()->get(); $users = DB::table('users')->select('name as user_name')->get(); 

增加查詢子句到現有的查詢中

$query = DB::table('users')->select('name'); $users = $query->addSelect('age')->get(); 

使用 where 及運算符

$users = DB::table('users')->where('votes', '>', 100)->get(); 

「or」語法

$users = DB::table('users') ->where('votes', '>', 100) ->orWhere('name', 'John') ->get(); 

使用 Where Between

$users = DB::table('users') ->whereBetween('votes', [1, 100])->get(); 

使用 Where Not Between

$users = DB::table('users') ->whereNotBetween('votes', [1, 100])->get(); 

使用 Where In 與數組

$users = DB::table('users') ->whereIn('id', [1, 2, 3])->get(); $users = DB::table('users') ->whereNotIn('id', [1, 2, 3])->get(); 

使用 Where Null 找有未配置的值的數據

$users = DB::table('users') ->whereNull('updated_at')->get(); 

Dynamic Where Clauses

You may even use "dynamic" where statements to fluently build where statements using magic methods:

$admin = DB::table('users')->whereId(1)->first(); $john = DB::table('users') ->whereIdAndEmail(2, 'john@doe.com') ->first(); $jane = DB::table('users') ->whereNameOrAge('Jane', 22) ->first(); 

排序(Order By)、分群(Group By) 及 Having

$users = DB::table('users') ->orderBy('name', 'desc') ->groupBy('count') ->having('count', '>', 100) ->get(); 

偏移(Offset) 及 限制(Limit)

$users = DB::table('users')->skip(10)->take(5)->get(); 

 

Joins

查詢構造器也可以使用 join 語法,看看下面的例子:

基本的 Join 語法

DB::table('users') ->join('contacts', 'users.id', '=', 'contacts.user_id') ->join('orders', 'users.id', '=', 'orders.user_id') ->select('users.id', 'contacts.phone', 'orders.price') ->get(); 

Left Join 語法

DB::table('users') ->leftJoin('posts', 'users.id', '=', 'posts.user_id') ->get(); 

你也可以指定更高級的 join 子句:

DB::table('users') ->join('contacts', function($join) { $join->on('users.id', '=', 'contacts.user_id')->orOn(...); }) ->get(); 

如果你想在你的 join 中使用 where 型式的子句,你可以在 join 子句里使用 where 或orWhere 方法。下面的方法將會比較 contacts 數據表中的 user_id 的數值,而不是比較兩個字段。

DB::table('users') ->join('contacts', function($join) { $join->on('users.id', '=', 'contacts.user_id') ->where('contacts.user_id', '>', 5); }) ->get(); 

 

高級 Wheres

群組化參數

有些時候你需要更高級的 where 子句,如「where exists」或嵌套的群組化參數。Laravel 的查詢構造器也可以處理這樣的情況:

DB::table('users') ->where('name', '=', 'John') ->orWhere(function($query) { $query->where('votes', '>', 100) ->where('title', '<>', 'Admin'); }) ->get(); 

上面的查找語法會產生下方的 SQL:

select * from users where name = 'John' or (votes > 100 and title <> 'Admin') 

Exists 語法

DB::table('users') ->whereExists(function($query) { $query->select(DB::raw(1)) ->from('orders') ->whereRaw('orders.user_id = users.id'); }) ->get(); 

上面的查找語法會產生下方的 SQL:

select * from users where exists ( select 1 from orders where orders.user_id = users.id ) 

 

聚合

查找產生器也提供各式各樣的聚合方法,如 countmaxminavg 及 sum

使用聚合方法

$users = DB::table('users')->count(); $price = DB::table('orders')->max('price'); $price = DB::table('orders')->min('price'); $price = DB::table('orders')->avg('price'); $total = DB::table('users')->sum('votes'); 

 

原生表達式

有些時候你需要使用原生表達式在查找語句里,這樣的表達式會成為字串插入至查找,因此要小心勿建立任何 SQL 注入點。要建立原生表達式,你可以使用 DB::raw 方法:

使用原生表達式

$users = DB::table('users') ->select(DB::raw('count(*) as user_count, status')) ->where('status', '<>', 1) ->groupBy('status') ->get(); 

 

添加

添加數據進數據表

DB::table('users')->insert( ['email' => 'john@example.com', 'votes' => 0] ); 

添加自動遞增 (Auto-Incrementing) ID 的數據至數據表

如果數據表有自動遞增的ID,可以使用 insertGetId 添加數據並返回該 ID:

$id = DB::table('users')->insertGetId( ['email' => 'john@example.com', 'votes' => 0] ); 

注意: 當使用 PostgreSQL 時,insertGetId 方法會預期自動增加的字段是以「id」為命名。

添加多個數據進數據表

DB::table('users')->insert([ ['email' => 'taylor@example.com', 'votes' => 0], ['email' => 'dayle@example.com', 'votes' => 0] ]); 

 

更新

更新數據表中的數據

DB::table('users') ->where('id', 1) ->update(['votes' => 1]); 

自增或自減一個字段的值

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']); 

 

刪除

刪除數據表中的數據

DB::table('users')->where('votes', '<', 100)->delete(); 

刪除數據表中的所有數據

DB::table('users')->delete(); 

清空數據表

DB::table('users')->truncate(); 

 

Unions

查詢構造器也提供一個快速的方法去「合並 (union)」兩個查找的結果:

$first = DB::table('users')->whereNull('first_name'); $users = DB::table('users')->whereNull('last_name')->union($first)->get(); 

unionAll 方法也可以使用,它與 union 方法的使用方式一樣。

 

悲觀鎖定 (Pessimistic Locking)

查詢構造器提供了少數函數協助你在 SELECT 語句中做到「悲觀鎖定」。

想要在 SELECT 語句中加上「Shard lock」,只要在查找語句中使用 sharedLock 函數:

DB::table('users')->where('votes', '>', 100)->sharedLock()->get(); 

要在 select 語法中使用「鎖住更新(lock for update)」時,你可以使用 lockForUpdate方法:

DB::table('users')->where('votes', '>', 100)->lockForUpdate()->get();


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM