如何在Laravel中划分read/write数据库设置?

How to divide read/write database setting in Laravel?

这是Laravel中数据库划分设置的推荐规则。

'mysql' => [
    'read' => [
                  'host' => '192.168.1.1',
              ],
   'write' => [
                  'host' => '196.168.1.2'
              ],
      'sticky'    => true,
      'driver'    => 'mysql',
      'database'  => 'database',
      'username'  => 'root',
      'password'  => '',
      'charset'   => 'utf8mb4',
      'collation' => 'utf8mb4_unicode_ci',
      'prefix'    => '',
  ],  

但是如果我想对每个read/write数据库使用不同的访问信息如DB_NAME、USER_ID、PASS等,那我该怎么做呢?谢谢。

您可以像这样声明另一个数据库连接:

'mysql' => [
    'read' => [
                  'host' => '192.168.1.1',
              ],
   'write' => [
                  'host' => '192.168.1.1'
              ],
      'sticky'    => true,
      'driver'    => 'mysql',
      'database'  => 'database',
      'username'  => 'root',
      'password'  => '',
      'charset'   => 'utf8mb4',
      'collation' => 'utf8mb4_unicode_ci',
      'prefix'    => '',
], 

'writecon' => [
    'read' => [
        'host' => '196.168.1.2',
    ],
    'write' => [
        'host' => '196.168.1.2'
    ],
    'driver' => 'mysql',
    'port' => env('DB2_PORT', '3306'),
    'database' => env('DB2_DATABASE', 'db2'),
    'username' => env('DB2_USERNAME', 'somename'),
    'password' => env('DB2_PASSWORD', 'somepass'),
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix' => '',
],

然后在你的 .env 中添加:

DB2_PORT=3306
DB2_DATABASE=db2
DB2_USERNAME=somename
DB2_PASSWORD=somepass

你可以这样使用它:

$someModel->setConnection('writecon');
$someModel->save();

未测试,但您可以尝试。

您可以创建两个连接,然后使用 on 方法指定与 Eloquent 的连接:

'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ],
'mysql2' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST2', '127.0.0.1'),
            'port' => env('DB_PORT2', '3306'),
            'database' => env('DB_DATABASE2', 'forge'),
            'username' => env('DB_USERNAME2', 'forge'),
            'password' => env('DB_PASSWORD2', ''),
            'unix_socket' => env('DB_SOCKET2', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ],


User::on('mysql2')->where('id', $id)->update($data);


或使用查询生成器:

DB::connection('mysql2')->table('users')->where('id', $id)->update($data);