ユーザ用ツール

サイト用ツール


サイドバー

このページの翻訳:



最近の更新



Tag Cloud

11_php:02_framework:01_laravel:17_laravel_multiple_database

17 Laravel 複数データベース接続

Laravel 5.x

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database1
DB_USERNAME=root
DB_PASSWORD=secret
 
DB_CONNECTION_SECOND=mysql
DB_HOST_SECOND=127.0.0.1
DB_PORT_SECOND=3306
DB_DATABASE_SECOND=database2
DB_USERNAME_SECOND=root
DB_PASSWORD_SECOND=secret

config/database.php

'mysql' => [
    'driver'    => env('DB_CONNECTION'),
    'host'      => env('DB_HOST'),
    'port'      => env('DB_PORT'),
    'database'  => env('DB_DATABASE'),
    'username'  => env('DB_USERNAME'),
    'password'  => env('DB_PASSWORD'),
],
 
'mysql2' => [
    'driver'    => env('DB_CONNECTION_SECOND'),
    'host'      => env('DB_HOST_SECOND'),
    'port'      => env('DB_PORT_SECOND'),
    'database'  => env('DB_DATABASE_SECOND'),
    'username'  => env('DB_USERNAME_SECOND'),
    'password'  => env('DB_PASSWORD_SECOND'),
],

Laravel 4.X

app/config/database.php

return array(
 
    'default' => 'mysql',
 
    'connections' => array(
 
        # Primary/Default database connection
        'mysql' => array(
            'driver'    => 'mysql',
            'host'      => '127.0.0.1',
            'database'  => 'database1',
            'username'  => 'root',
            'password'  => 'secret'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),
 
        # Secondary database connection
        'mysql2' => array(
            'driver'    => 'mysql',
            'host'      => '127.0.0.1',
            'database'  => 'database2',
            'username'  => 'root',
            'password'  => 'secret'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),
    ),
);

複数のデータベースに接続コントロール側

Schemaでデータベースへ接続

Schema::connection('mysql2')->create('some_table', function($table)
{
    $table->increments('id'):
});

Query Builderでデータベースへ接続

$users = DB::connection('mysql2')->select(...);

DB::talbe()の形で利用する

$users = DB::connection('mysql2')->talbe('users')->limit(100);

print_r($users->first());

Eloquent ORMでデータベースへ接続

<?php
 
class SomeModel extends Eloquent {
 
    protected $connection = 'mysql2';
 
}
<?php
 
class SomeController extends BaseController {
 
    public function someMethod()
    {
        $someModel = new SomeModel;
 
        $someModel->setConnection('mysql2');
 
        $something = $someModel->find(1);
 
        return $something;
    }
 
}
11_php/02_framework/01_laravel/17_laravel_multiple_database.txt · 最終更新: 2019/03/27 18:33 by matsui