Laravel 使用多個資料庫連線

曉軒發表於2018-08-27

1、配置.env檔案

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

DB_HOST_CENTER=127.0.0.1
DB_PORT_CENTER=3306
DB_DATABASE_CENTER=database_center
DB_USERNAME_CENTER=root
DB_PASSWORD_CENTER=

2、配置config/database.php

'mysql' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', 'localhost'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'charset' => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix' => '',
        'strict' => false,
        'engine' => null,
],
'mysql_center' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST_CENTER', 'localhost'),
        'port' => env('DB_PORT_CENTER', '3306'),
        'database' => env('DB_DATABASE_CENTER', 'forge'),
        'username' => env('DB_USERNAME_CENTER', 'forge'),
        'password' => env('DB_PASSWORD_CENTER', ''),
        'charset' => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix' => '',
        'strict' => false,
        'engine' => null,
],

3、建立model

a、這個model將採用預設的'mysql'連線
class UserModel extends Model
{
        // 資料庫'database'中的users表
        protected $table = "users";
}

b、 這個model將使用mysql_center連線
class UserModel extends Model
{
    // 資料庫'dadtabase_center'中的users表
        protected $connection = 'mysql_center';
        protected $table = "users";

}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

不要輕易放棄。學習成長的路上,我們長路漫漫,只因學無止境

Don't give up easily. On the way of learning and growing up, we have a long way to go, just because there is no end to learning.

相關文章