配置
illuminate/database 數(shù)據(jù)庫(kù)及版本支持情況如下:
- MySQL 5.6+
- PostgreSQL 9.4+
- SQLite 3.8.8+
-
SQL Server 2017+
數(shù)據(jù)庫(kù)配置文件位置為
config/database.php
。return [ // 默認(rèn)數(shù)據(jù)庫(kù) 'default' => 'mysql', // 各種數(shù)據(jù)庫(kù)配置 'connections' => [ 'mysql' => [ 'driver' => 'mysql', 'host' => '127.0.0.1', 'port' => 3306, 'database' => 'webman', 'username' => 'webman', 'password' => '', 'unix_socket' => '', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', 'strict' => true, 'engine' => null, ], 'sqlite' => [ 'driver' => 'sqlite', 'database' => '', 'prefix' => '', ], 'pgsql' => [ 'driver' => 'pgsql', 'host' => '127.0.0.1', 'port' => 5432, 'database' => 'webman', 'username' => 'webman', 'password' => '', 'charset' => 'utf8', 'prefix' => '', 'schema' => 'public', 'sslmode' => 'prefer', ], 'sqlsrv' => [ 'driver' => 'sqlsrv', 'host' => 'localhost', 'port' => 1433, 'database' => 'webman', 'username' => 'webman', 'password' => '', 'charset' => 'utf8', 'prefix' => '', ], ], ];
使用多個(gè)數(shù)據(jù)庫(kù)
通過(guò)
Db::connection('配置名')
來(lái)選擇使用哪個(gè)數(shù)據(jù)庫(kù),其中配置名
為配置文件config/database.php
中的對(duì)應(yīng)配置的key
。例如如下數(shù)據(jù)庫(kù)配置:
return [
// 默認(rèn)數(shù)據(jù)庫(kù)
'default' => 'mysql',
// 各種數(shù)據(jù)庫(kù)配置
'connections' => [
'mysql' => [
'driver' => 'mysql',
'host' => '127.0.0.1',
'port' => 3306,
'database' => 'webman',
'username' => 'webman',
'password' => '',
'unix_socket' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
'mysql2' => [
'driver' => 'mysql',
'host' => '127.0.0.1',
'port' => 3306,
'database' => 'webman2',
'username' => 'webman2',
'password' => '',
'unix_socket' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
'pgsql' => [
'driver' => 'pgsql',
'host' => '127.0.0.1',
'port' => 5432,
'database' => 'webman',
'username' => 'webman',
'password' => '',
'charset' => 'utf8',
'prefix' => '',
'schema' => 'public',
'sslmode' => 'prefer',
],
];
像這樣切換數(shù)據(jù)庫(kù)。
// 使用默認(rèn)數(shù)據(jù)庫(kù),等價(jià)于Db::connection('mysql')->table('users')->where('name', 'John')->first();
$users = Db::table('users')->where('name', 'John')->first();;
// 使用mysql2
$users = Db::connection('mysql2')->table('users')->where('name', 'John')->first();
// 使用pgsql
$users = Db::connection('pgsql')->table('users')->where('name', 'John')->first();