May 31, 2017

Laravel5 - Working on multiple DB.

Some reasons you need multiple DB when you making test migration on current working application.
Like my case, you are currently working on postgresql which the old DB in in mysql. Which tester the current posgre DB. I cant made that DB as my migration destination. This I why I need multiple DB configuration.

Here simple thing I did.

* Configure database setting(config/database.php) to defined mutiple DB.
return [
    'default' => env('DB_CONNECTION', 'pgsql'),
    'fetch' => PDO::FETCH_ASSOC, 
    'connections' => [
        'pgsql' => [
            'driver' => 'pgsql',
            'host' => env('DB_HOST'),
            'database' => env('DB_DATABASE'),
            'username' => env('DB_USERNAME'),
            'password' => env('DB_PASSWORD'),
            'charset'  => env('DB_CHARSET', 'utf8'),
            'prefix'   => env('DB_PREFIX', ''),
            'schema'   => env('DB_SCHEMA', 'core'),
        ],
        
        /*
         * START -
         * Migration Tesd DB
         */
        'migration' => [
            // My Postgre DB Destination
            'driver' => 'pgsql',
            'host' => 'localhost'
            'database' => 'dest_db',
            'username' => 'myuser,
            'password' => 'MyPaswordd',
            'charset'  => env('DB_CHARSET', 'utf8'),
            'prefix'   => env('DB_PREFIX', ''),
            'schema'   => env('DB_SCHEMA', 'core'),
        ],
        'mysql' => [
            // Source Mysql DB Data.
            'driver'    => 'mysql',
            'host'      => '192.168.101.17',
            'port'      => 3306,
            'database'  => 'src_db',
            'username'  => 'myuser',
            'password'  => 'mypassword',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            //'timezone'  => env('DB_TIMEZONE', '+00:00'),
            'strict'    => env('DB_STRICT_MODE', false),
        ],
    ],
];


While Working on migration script. I learn to use the Console feature of laravel.

$users = DB::connection('mysql')
    ->select('SELECT * FROM users '
        . 'limit 10' // For testing I put limit
    );

foreach($users as $user){
    // Create as object since "setConnection" none static
    $myuser = new \App\Model\App\Users();
    // Store the user to PSQL.
    // Assume the old and new table are same field names
    $myuser->setConnection('migration')
            ->store($user);

}