美文网首页程序员
laravel切换数据库

laravel切换数据库

作者: 闲睡猫 | 来源:发表于2019-03-26 17:46 被阅读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();

相关文章

网友评论

    本文标题:laravel切换数据库

    本文链接:https://www.haomeiwen.com/subject/ufynvqtx.html