企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[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。