laravel / lumen 使用多个数据库连接

1、配置.env文件

DB_CONNECTION=db_a
DB_TIMEZONE=+08:00
DB_CHARSET=utf8mb4
DB_COLLATION=utf8mb4_general_ci

DB_OPT_HOST=dev
DB_OPT_PORT=3306
DB_OPT_DATABASE=db_a_name
DB_OPT_USERNAME=hjm_dev
DB_OPT_PASSWORD=hjm_dev
DB_OPT_PREFIX=h_

DB_MKT_HOST=dev
DB_MKT_PORT=3306
DB_MKT_DATABASE=db_b_name
DB_MKT_USERNAME=hjm_dev
DB_MKT_PASSWORD=hjm_dev

DB_THIRD_HOST=dev
DB_THIRD_PORT=3306
DB_THIRD_DATABASE=db_c_name
DB_THIRD_USERNAME=hjm_dev
DB_THIRD_PASSWORD=hjm_dev
DB_THIRD_PREFIX=h_

2、配置config/database.php

        'db_a' => [
            'driver'    => 'mysql',
            'host'      => env('DB_OPT_HOST', 'localhost'),
            'port'      => env('DB_OPT_PORT', 3306),
            'database'  => env('DB_OPT_DATABASE', 'forge'),
            'username'  => env('DB_OPT_USERNAME', 'forge'),
            'password'  => env('DB_OPT_PASSWORD', ''),
            'prefix'    => env('DB_OPT_PREFIX', ''),
            'charset'   => env('DB_CHARSET', 'utf8mb4'),
            'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),
            'timezone'  => env('DB_TIMEZONE', '+00:00'),
            'strict'    => env('DB_STRICT_MODE', false),
        ],

        'db_b' => [
            'driver'    => 'mysql',
            'host'      => env('DB_MKT_HOST', 'localhost'),
            'port'      => env('DB_MKT_PORT', 3306),
            'database'  => env('DB_MKT_DATABASE', 'forge'),
            'username'  => env('DB_MKT_USERNAME', 'forge'),
            'password'  => env('DB_MKT_PASSWORD', ''),
            'prefix'    => env('DB_MKT_PREFIX', ''),
            'charset'   => env('DB_CHARSET', 'utf8mb4'),
            'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),
            'timezone'  => env('DB_TIMEZONE', '+00:00'),
            'strict'    => env('DB_STRICT_MODE', false),
        ],

        'db_c' => [
            'driver'    => 'mysql',
            'host'      => env('DB_THIRD_HOST', 'localhost'),
            'port'      => env('DB_THIRD_PORT', 3306),
            'database'  => env('DB_THIRD_DATABASE', 'forge'),
            'username'  => env('DB_THIRD_USERNAME', 'forge'),
            'password'  => env('DB_THIRD_PASSWORD', ''),
            'prefix'    => env('DB_THIRD_PREFIX', ''),
            'charset'   => env('DB_CHARSET', 'utf8mb4'),
            'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),
            'timezone'  => env('DB_TIMEZONE', '+00:00'),
            'strict'    => env('DB_STRICT_MODE', false),
        ],

 

3、创建model

class TestModel extends Model
{
    /**
     * 定义链接数据库
     * @var string
     */
    protected $connection = 'db_a';

 

你可能感兴趣的:(PHP,laravel)