1 配置信息
1.1配置目錄:
config/database.php
1.2配置多個數據庫
//默認的數據庫
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '3306'),
//更多配置
],
//能夠建立更多的數據庫
'mysql' => [
'driver' => 'mysql_2',
'host' => env('DB_HOST', '192.168.1.2'),
'port' => env('DB_PORT', '3306'),
//更多配置
],
2 使用DB門面進行基本操做
一旦你設置好了數據庫鏈接,就能夠使用 DB facade 來進行查找。DB facade 提供每一個類型的查找方法:select、update、insert、delete、statement。
2.1增->
DB::insert('insert into users (id, name) values (?, ?)', [1, 'Dayle']);
2.2刪->
$deleted = DB::delete('delete from users');
返回值:刪除的行數將會被返回
2.3改->
$affected = DB::update('update users set votes = 100 where name = ?', ['John']);
返回值:該方法會返回此聲明所影響的行數
2.4查->
$users = DB::select('select * from users where active = ?', [1]);
返回值:方法總會返回結果的數組數據。數組中的每一個結果都是一個 PHP StdClass 對象,這使你可以訪問到結果的值:
訪問方法:
foreach ($users as $user) {
echo $user->name;
}
2.5事務處理->
//自動
DB::transaction(function () {
DB::table('users')->update(['votes' => 1]);
DB::table('posts')->delete();
});
//手動(可配合try catch使用)
DB::beginTransaction();
if($someContion){
DB::rollback();
return false;
}
DB::commit();
2.6有時候一些數據庫操做不該該返回任何參數。對於這種類型的操做,你能夠在 DB facade 使用 statement 方法:
DB::statement('drop table users');
3 查詢構造器
爲何要使用查詢構造器?
1>由於數據庫查詢構造器提供了方便、流暢的接口,咱們不須要再寫原生的sql語句,經過查詢構造器提供給咱們的各類方法來建立及運行數據庫查找。這可以知足咱們大部分須要,且能在全部被支持的數據庫系統中使用。
2>Laravel 的查詢構造器使用 PDO 參數綁定,以保護你的應用程序不受數據庫注入攻擊。在傳入字符串做爲綁定前不須要先清理它們。
如何獲得一個查詢構造器:
依賴DB門面,使用它提供給咱們的table方法,傳入表名,便可獲取該表的查詢構建器,在此基礎上咱們能夠使用強大的鏈式調用直到獲得最終結果。
3.1 獲取結果
3.1.1 從數據表中獲取全部的數據列
$users = DB::table('users')->get();
返回值: 一個數組結果,其中每個結果都是 PHP StdClass 對象的實例,能夠將列做爲屬性訪問每一個列的值。
訪問方法:
foreach ($users as $user) {
echo $user->name;
//操做的是對象的屬性
}
3.1.2 從數據表中獲取單個列或行
1>取出單行數據,使用first 方法。
$user = DB::table('users')->where('name', 'John')->first();
返回值:單個 StdClass 對象: 訪問方法:echo $user->name;
2>從單行數據中取出單個值,使用 value 方法。
$email = DB::table('users')->where('name', 'John')->value('email');
返回值:直接返回字段的值:
3.1.3 從數據表中將結果切塊
若你須要操做數千條數據庫記錄,則可考慮使用 chunk 方法。這個方法一次只取出一小「塊」結果,並會將每一個區塊傳給一個閉包進行處理。
例如,讓咱們將整個 user 數據表進行切塊,每次處理 100 條記錄:
DB::table('users')->chunk(100, function($users) {
foreach ($users as $user) {
//
}
});
你能夠從閉包中返回 false,以中止對後續切塊的處理:
DB::table('users')->chunk(100, function($users) {
// 處理記錄…
return false;
});
3.1.4 獲取字段值列表
若你想要獲取一個包含單個字段值的數組,你能夠使用pluck方法
$titles = DB::table('roles')->pluck('title');
返回值:在這個例子中,咱們將取出 role 數據表 title 字段的數組:
使用方法:
foreach ($titles as $title) {
echo $title;
}
你也能夠在返回的數組中指定自定義的鍵值字段:
$roles = DB::table('roles')->pluck('title', 'name');
foreach ($roles as $name => $title) {
echo $title;
}
3.2 select的用法
3.2.1 指定一個 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();
3.2.2 原始表達式
//DB::raw 方法能夠防止注入
$users = DB::table('users') ->select(DB::raw('count(*) as user_count, status')) ->where('status', '<>', 1) ->groupBy('status') ->get();
3.3 join的用法
3.3.1 基本用法(inner 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,rightjoin替換join便可
3.3.2 高級的 Join 語法
你也能夠指定更高級的 join 子句。讓咱們以傳入一個閉包看成 join 方法的第二參數來做爲開始。此閉包會接收 JoinClause 對象,讓你能夠在 join 子句上指定約束:
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();
這裏要提一下若是閉包函數functiton(){}中5是個變量,咱們須要傳過去那麼應該這樣寫
function ($join) use($num){ $join->on('users.id', '=', 'contacts.user_id') ->where('contacts.user_id', '>', $num);
若是沒有use($num)外面的$num是無法傳遞到where子句的
3.4 where的用法
3.4.1 基本用法
$users = DB::table('users')->where('votes', '=', 100)->get();
$users = DB::table('users')->where('name', 'like', 'T%')->get();
$users = DB::table('users')->where('votes', 100)->get(); //省略了等號
$users = DB::table('users')->where('votes', '>', 100) ->orWhere('name', 'John')->get();
$users = DB::table('users')->whereBetween('votes', [1, 100])->get(); //一個字段的值介於兩個值之間
$users = DB::table('users')->whereNotBetween('votes', [1, 100])->get(); //一個字段的值落在兩個值以外
$users = DB::table('users')->whereIn('id', [1, 2, 3])->get(); //字段的值包含在指定的數組以內
$users = DB::table('users')->whereNotIn('id', [1, 2, 3])->get(); //字段的值不包含在指定的數組以內
$users = DB::table('users')->whereNull('updated_at')->get(); //指定列的值爲 NULL
$users = DB::table('users')->whereNotNull('updated_at')->get(); //一個列的值不爲 NULL
3.4.2 高級用法
將約束分組
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')
3.5 orderBy,groupBy,having
//排序
$users = DB::table('users') ->orderBy('name', 'desc') ->get();
//隨機排序
$randomUser = DB::table('users') ->inRandomOrder() ->first();
//分組
$users = DB::table('users') ->groupBy('account_id') ->having('account_id', '>', 100) ->get();
//havingRaw 方法可用來將原始字符串設置爲 having 子句的值
$users = DB::table('orders') ->select('department', DB::raw('SUM(price) as total_sales')) ->groupBy('department') ->havingRaw('SUM(price) > 2500') ->get();
3.6 條件查詢語句
能夠使用方法 when 來構建條件查詢語句,只有當 when 的第一次參數爲 true 的話,匿名函數裏的 where 語句纔會被執行:
$role = $request->input('role');
$users = DB::table('users')
->when($role, function ($query) use ($role) {
return $query->where('role_id', $role);
})
->get();
3.7 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,則可以使用 insertGetId 方法來插入記錄並獲取其 ID:
$id = DB::table('users')->insertGetId( ['email' => 'john@example.com', 'votes' => 0] );
3.8 update的用法
DB::table('users') ->where('id', 1) ->update(['votes' => 1]);
3.9 delete
DB::table('users')->delete();
DB::table('users')->where('votes', '<', 100)->delete();
//若你但願截去整個數據表的全部數據列,並將自動遞增 ID 重設爲零,則能夠使用 truncate 方法:
DB::table('users')->truncate();
3.10悲觀鎖定
查詢語句構造器也包含一些可用以協助你在 select 語法上做「悲觀鎖定」的函數。若要以「共享鎖」來運行語句,則可在查找上使用 sharedLock 方法。共享鎖可避免選擇的數據列被更改,直到事務被提交爲止:
DB::table('users')->where('votes', '>', 100)->sharedLock()->get();
此外,你也能夠使用 lockForUpdate 方法。「用以更新」鎖可避免數據列被其它共享鎖修改或選取:
DB::table('users')->where('votes', '>', 100)->lockForUpdate()->get();