0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

laravel 別のMYSQLに動的接続、切り替え

Last updated at Posted at 2020-08-30

laravel で 別のデータベースに切り替えたい時がある。
例えば、古いDBから新しいDBにデータを以降する時など。

今回は、database twiski に切り替たい

database.php

//色々と略
'connections' => [

'mysql' => [
    'driver' => 'mysql',
    'url' => env('DATABASE_URL'),
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', '3306'),
    'database' => env('DB_DATABASE', 'forge'),
],


'old' => [
    'driver' => 'mysql',
    'url' => env('DATABASE_URL'),
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', '3306'),
    'database' => 'twiski',//接続したいDBに書き換える
],


これで twiski に切り替えられる

HogeContorller.php

$model = new User;

$res = $model
    ->orderBy('id', 'ASC')
    ->first();

$res = $model
    ->setConnection('old')//これが味噌
    ->orderBy('id', 'ASC')
    ->first();


DBファサードを使う

これで oldusers テーブルのデータ取得できる

HogeController.php

//use DB;

$profiles_tags = DB::connection('old')
    ->table('users')
    ->limit(5)
    ->get();


以上

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?