Laravel 5.2辅助mysql数据库连接返回默认连接

时间:2018-01-04 12:45:11

标签: php laravel laravel-5.2

我正在尝试使用Laravel 5.2连接第二个mysql数据库。

database.php config:

[
    'fetch' => PDO::FETCH_CLASS,

    'default' => env('DB_CONNECTION', 'primary'),
    'connections' => [
        'primary' => [
            'driver'    => 'mysql',
            'host'      => env('DB_HOST', ''),
            'database'  => env('DB_DATABASE', ''),
            'username'  => env('DB_USERNAME', ''),
            'password'  => env('DB_PASSWORD', ''),
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'strict'    => false,
        ],

        'secondary' => [
            'driver'    => 'mysql',
            'host'      => 'secondary.host',
            'database'  => env('DB_DATABASE', ''),
            'username'  => env('DB_USERNAME', ''),
            'password'  => env('DB_PASSWORD', ''),
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'strict'    => false,
        ],
    ],

    'migrations' => 'migrations',

    'redis' => [

        'cluster' => false,

        'default' => [
            'host'     => '127.0.0.1',
            'port'     => 6379,
            'database' => 0,
        ],

    ],
];

代码:

<?php


namespace App\Objects;

use DB;

class Test
{
    private $db;
    public function __construct() {
        $this->db = DB::connection('secondary');
        // Read stuff from the secondary database, for example:
        dump($this->db->select('SELECT * FROM addresses LIMIT 1;'));
    }
}

以某种方式连接DB::connection('secondary')返回的是我的主数据库连接。

深入挖掘laravel核心后,我注意到:Illuminate\Database\Connectors\ConnectionFactory::createConnection返回错误的连接。

2 个答案:

答案 0 :(得分:0)

您需要为每个查询指定连接:

DB::connection('secondary')->table('users')->where('id', 1)->get();

https://laravel.com/docs/5.5/database#using-multiple-database-connections

答案 1 :(得分:0)

两个连接都有相同的env变量。您需要为每个连接设置不同的变量:

DB_DATABASE_PRIMARY
DB_DATABASE_SECONDARY

所有其他变量的示例。