首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

Laravel 資料庫連線進階:讀寫分離、事務、查詢日誌與多連線管理

     編輯:PHP 綜合知識

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() 記錄慢查詢

善用進階資料庫功能能顯著提升應用效能與穩定性。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved