程序员

laravel切换数据库

2019-03-26  本文已影响0人  闲睡猫

设置多个数据库连接

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=test
DB_USERNAME=root
DB_PASSWORD=root

DB_OTHER_HOST=127.0.0.1
DB_OTHER_PORT=3306
DB_OTHER_DATABASE=other
DB_OTHER_USERNAME=root
DB_OTHER_PASSWORD=root
image

config/database.phpconnections 选项中加上新增数据库连接配置:

// 新增的数据库连接
'mysql_auction' => [
    'driver' => 'mysql',
    'host' => env('DB_OTHER_HOST'),
    'port' => env('DB_OTHER_PORT'),
    'database' => env('DB_OTHER_DATABASE'),
    'username' => env('DB_OTHER_USERNAME'),
    'password' => env('DB_OTHER_PASSWORD'),
    'unix_socket' => env('DB_SOCKET', ''),
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix' => '',
    'prefix_indexes' => true,
    'strict' => true,
    'engine' => null,
],

切换数据库

使用默认的数据库连接:

DB::table('test')->first();

切换数据库:

DB::connection('mysql_other')->table('test')->first();
上一篇下一篇

猜你喜欢

热点阅读