laravel 使用不同的字首連線模型。
資料庫配置 config/database.php
...
'connections' => [
'mysql' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', 'mysql'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'default'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', 'xxx'),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => env('DB_PREFIX', 'zbc_'),
'prefix_indexes' => true,
'strict' => false,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter(
[
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]
) : [],
],
'mysql2' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', 'mysql'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'default'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', 'xxxxxx'),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'strict' => false,
'engine' => null,
],
],
...
編寫migrate 檔案時新增connection 指定資料庫配置連線。 database/migrations/2021_03_11_170106_test.php
Schema::connection('mysql2')->table(
'system_setting',
function (Blueprint $table) {
$table->string('test', 300)->comment('測試')->nullable();
}
);
執行後如果發現讀取不對,還是讀的之前的mysql連線
- 原因:config 快取了之前的mysql配置
- 解決:執行artisan 命令清除config配置快取。
php artisan config:clear
本作品採用《CC 協議》,轉載必須註明作者和本文連結