多個資料庫連線

Laravel 允許使用者處理多個資料庫連線。如果需要連線到多個資料庫並使它們協同工作,則需要注意連線設定。

如果需要,還允許在同一應用程式中使用不同型別的資料庫。

預設連線config/database.php 中,你可以看到配置項呼叫:

'default' => env('DB_CONNECTION', 'mysql'),

此名稱引用下面的連線名稱 mysql

'connections' => [

    'sqlite' => [
        'driver' => 'sqlite',
        'database' =>  database_path('database.sqlite'),
        'prefix' => '',
    ],

    '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,
    ],
],

如果你未在其他程式碼或命令中提及資料庫連線的名稱,Laravel 將選擇預設的資料庫連線名稱。但是,在多個資料庫連線中,即使你設定了預設連線,也可以更好地設定你使用的資料庫連線。

遷移檔案

在遷移檔案中,如果是單個資料庫連線,則可以使用:

 Schema::create("table",function(Blueprint $table){
     $table->increments('id');
});

在多資料庫連線中,你將使用 connection() 方法告訴 Laravel 你使用的資料庫連線:

 Schema::connection("sqlite")->create("table",function(Blueprint $table){
     $table->increments('id');
});

工匠移民

如果使用單個資料庫連線,則將執行:

php artisan migrate

但是,對於多個資料庫連線,你最好告訴哪個資料庫連線維護遷移資料。所以你將執行以下命令:

php artisan migrate:install --database=sqlite

此命令將在目標資料庫中安裝遷移表以準備遷移。

php artisan migrate --database=sqlite

此命令將執行遷移並將遷移資料儲存在目標資料庫中

php artisan migrate:rollback --database=sqlite

此命令將回滾遷移並將遷移資料儲存在目標資料庫中

雄辯的模型

要使用 Eloquent 指定資料庫連線,你需要定義 $connection 屬性:

namespace App\Model\Sqlite;
class Table extends Model
{
    protected $table="table";
    protected $connection = 'sqlite';
}

使用 Eloquent 指定另一個(第二個)資料庫連線:

namespace App\Model\MySql;
class Table extends Model
{
    protected $table="table";
    protected $connection = 'mysql';
}

Laravel 將使用模型中定義的 $connection 屬性來利用 config/database.php 中定義的指定連線。如果未在模型中定義 $connection 屬性,則將使用預設值。

你還可以使用靜態 on 方法指定另一個連線:

// Using the sqlite connection
Table::on('sqlite')->select(...)->get()
// Using the mysql connection
Table::on('mysql')->select(...)->get()

資料庫/查詢生成器

你還可以使用查詢構建器指定另一個連線:

// Using the sqlite connection
DB::connection('sqlite')->table('table')->select(...)->get()
// Using the mysql connection
DB::connection('mysql')->table('table')->select(...)->get()  

單元測試

Laravel 提供 seeInDatabase($table,$fielsArray,$connection) 來測試資料庫連線程式碼。在單元測試檔案中,你需要執行以下操作:

$this
    ->json(
        'GET',
        'result1/2015-05-08/2015-08-08/a/123'
    )
     ->seeInDatabase("log", ["field"=>"value"], 'sqlite');

通過這種方式,Laravel 將知道要測試的資料庫連線。

單元測試中的資料庫事務

Laravel 允許資料庫在測試期間回滾所有更改。要測試多個資料庫連線,需要設定 $connectionsToTransact 屬性

use Illuminate\Foundation\Testing\DatabaseMigrations;

class ExampleTest extends TestCase
{
     use DatabaseTransactions;

     $connectionsToTransact =["mysql","sqlite"] //tell Laravel which database need to rollBack

    public function testExampleIndex()
    {
        $this->visit('/action/parameter')
         ->see('items');
    }
}