[TOC]
# 快速入門
## 簡介
Laravel 目前支持四種數據庫:MySQL、PostgreSQL、SQLite、SQL Server,數據庫的配置文件放置在 config/database.php 文件中。
## 配置
### SQLite 配置
```
// 使用數據庫的絕對路徑配置環境變量
DB_CONNECTION=sqlite
DB_DATABASE=/absolute/path/to/database.sqlite
// 如果要開啟 SQLite 連接的外鍵約束,應該將 foreign_key_constraints
// 添加到 config/database.php 配置文件中
'sqlite' => [
// ...
'foreign_key_constraints' => true,
],
```
### 讀寫分離配置
```
'mysql' => [
'read' => [
'host' => [
'192.168.1.1',
'196.168.1.2',
],
],
'write' => [
'host' => ['196.168.1.2'],
],
'sticky' => true,
'driver' => 'mysql',
'database' => 'database',
'username' => 'root',
'password' => '',
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
],
```
`sticky`是一個*可選值*,它可用于立即讀取在當前請求周期內已寫入數據庫的記錄。若`sticky`選項被啟用,并且當前請求周期內執行過 「寫」 操作,那么任何 「讀」 操作都將使用 「寫」 連接。這樣可確保同一個請求周期內寫入的數據可以被立即讀取到,從而避免主從延遲導致數據不一致的問題。不過是否啟用它,取決于應用程序的需求。
### 使用多個數據庫連接
```
// connection 方法的參數在 config/database.php 文件的 connections 數組中配置
$users = DB::connection('foo')->select(...);
// 使用連接實例上的 getPdo 方法訪問底層的 PDO 實例
$pdo = DB::connection()->getPdo();
```
## 運行原生 SQL 查詢
### Select 查詢
```
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
/**
* 顯示應用程序中所有用戶的列表
*
* @return Response
*/
public function index()
{
$users = DB::select('select * from users where active = ?', [1]);
return view('user.index', ['users' => $users]);
}
}
// select 返回 StdClass 對象的數組
foreach ($users as $user) {
echo $user->name;
}
```
### 使用命名綁定
```
$results = DB::select('select * from users where id = :id', ['id' => 1]);
```
### 插入語句
```
// 返回 true 或報錯
DB::insert('insert into users (id, name) values (?, ?)', [1, 'Dayle']);
```
### 更新語句
```
// 返回語句影響的行數
$affected = DB::update('update users set votes = 100 where name = ?', ['John']);
```
### 刪除語句
```
// 返回語句影響的行數
$deleted = DB::delete('delete from users');
```
### 普通語句
```
// 沒有返回值
DB::statement('drop table users');
```
### 監聽查詢事件
```
// 在 AppServiceProvider 的 boot 方法設置
use Illuminate\Support\Facades\DB;
public function boot()
{
DB::listen(function ($query) {
// $query->sql
// $query->bindings
// $query->time
});
}
```
## 數據庫事務
```
// 事務的閉包出現異常,事務將會回滾
DB::transaction(function () {
DB::table('users')->update(['votes' => 1]);
DB::table('posts')->delete();
});
```
### 處理死鎖
```
// 可選第二個參數 ,該參數用來表示事務發生死鎖時重復執行的次數,嘗試次數完拋出異常。
DB::transaction(function () {
DB::table('users')->update(['votes' => 1]);
DB::table('posts')->delete();
}, 5);
```
### 手動使用事務
```
DB::beginTransaction();
try {
//
DB::commit();
} catch (\Exception $e) {
DB::rollBack();
//
}
```
>[success] 注意:DB facade 的事務方法同樣適用于 查詢構造器 和 Eloquent ORM。
- 入門指南
- 安裝
- 部署
- 基礎功能
- 路由
- 中間件
- CSRF 保護
- 控制器
- 請求
- 響應
- 視圖
- URL
- Session
- 表單驗證
- 錯誤
- 日志
- 前端開發
- Blade 模板
- 本地化
- 腳手架
- 編譯資源 Mix
- 安全相關
- 用戶認證
- API 認證
- 綜合話題
- 命令行
- 廣播
- 緩存
- 集合
- 事件
- 文件存儲
- 輔助函數
- 郵件發送
- 消息通知
- 擴展包開發
- 隊列
- 任務調度
- 數據庫
- 快速入門
- 查詢構造器
- 分頁
- 數據庫遷移
- 數據填充
- Redis
- Eloquent ORM
- 快速入門
- 速查表
- Artisan
- Auth
- Blade
- Cache
- Collection
- Composer
- Config
- Container
- Cookie
- DB
- Environment
- Event
- File
- Helper
- Input
- Lang
- Log
- Model
- Pagination
- Queue
- Redirect
- Request
- Response
- Route
- SSH
- Schema
- Security
- Session
- Storage
- String
- URL
- UnitTest
- Validation
- View