Laravel 資料庫層支援讀寫分離、彈性事務控制、查詢日誌記錄與多連線切換,本文系統整理進階配置與實務操作技巧。
// app/config/database.php
'mysql' => [
'read' => ['host' => '192.168.1.1'], // 讀庫
'write' => ['host' => '196.168.1.2'], // 寫庫
'driver' => 'mysql',
'database' => 'database',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
];
// 僅覆寫 host,其餘選項自動合併主設定
查詢構建器、Eloquent、原生查詢均自動路由至正確連線。
// Select
$results = DB::select('select * from users where id = ?', [1]);
// Insert
DB::insert('insert into users (id, name) values (?, ?)', [1, 'Dayle']);
// Update
$affected = DB::update('update users set votes = 100 where name = ?', ['John']);
// Delete
$affected = DB::delete('delete from users');
// 通用陳述
DB::statement('drop table users');
update/delete 回傳影響行數。
DB::listen(function($sql, $bindings, $time) {
// $sql: 完整 SQL
// $bindings: 綁定參數
// $time: 執行時間(毫秒)
});
DB::transaction(function() {
DB::table('users')->update(['votes' => 1]);
DB::table('posts')->delete();
// 例外自動回滾
});
DB::beginTransaction();
try {
// ...操作
DB::commit();
} catch (\Exception $e) {
DB::rollback();
throw $e;
}
// 指定連線
$users = DB::connection('foo')->select(...);
// 取得底層 PDO
$pdo = DB::connection()->getPdo();
// 重新連線
DB::reconnect('foo');
// 斷開連線(避免 max_connections 限制)
DB::disconnect('foo');
// 停用日誌(大量插入時節省記憶體) DB::connection()->disableQueryLog(); // 取得已執行查詢 $queries = DB::getQueryLog(); // 格式: [['query' => '...', 'bindings' => [...], 'time' => 1.23], ...]
disableQueryLog() + DB::transaction() 批次提交reconnect() 防止連線中斷DB::listen() 記錄慢查詢善用進階資料庫功能能顯著提升應用效能與穩定性。