다중 DB 연결 사용하기

Submitted by river - 등록 10 years ago - 수정 8 years ago

다중 DB 설정하기

app/config/database.php

<?php
return array(

    'default' => 'mysql',

    'connections' => array(

        # Our primary database connection
        'mysql' => array(
            'driver'    => 'mysql',
            'host'      => 'host1',
            'database'  => 'database1',
            'username'  => 'user1',
            'password'  => 'pass1'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),

        # Our secondary database connection
        'mysql2' => array(
            'driver'    => 'mysql',
            'host'      => 'host2',
            'database'  => 'database2',
            'username'  => 'user2',
            'password'  => 'pass2'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),
    ),
);

Schema

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

Query

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

Eloquent

<?php

class SomeModel extends Eloquent {

    protected $connection = 'mysql2';

}

setConnection 메서드를 이용한 동적 설정

<?php

class SomeController extends BaseController {

    public function someMethod()
    {
        $someModel = new SomeModel;

        $someModel->setConnection('mysql2');

        $something = $someModel->find(1);

        return $something;
    }

}

모델의 on 메서드 사용하는 방법

$user = User::on('connection-name')->find(1);
$user = User::onWriteConnection()->find(1);

Validation

$rules = array(
    'email' => 'unique:users,email_address'
);

$validator = Validator::make(Input::all(), $rules);
$validator->getPresenceVerifier()->setConnection('mysql2');
comments powered by Disqus