라 라벨에서 여러 데이터베이스를 사용하는 방법
시스템에 여러 데이터베이스를 결합하고 싶습니다. 대부분의 경우 데이터베이스는 MySQL입니다. 그러나 관리자는 이기종 데이터베이스 시스템의 소스를 사용 하는 보고서를 생성 할 수 있습니다 .
그래서 제 질문은 Laravel 이 그러한 상황을 처리하기 위해 Facade 를 제공 합니까? 또는 다른 프레임 워크가 문제에 더 적합한 기능을 가지고 있습니까?
사용 .env
> = 5.0 (5.5 테스트)
에 .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'),
],
참고 : 에서
mysql2
DB_username 및 DB_password가 동일한 경우, 당신은 사용할 수 있습니다env('DB_USERNAME')
에 metioned되는.env
처음 몇 줄.
.env
<5.0 없이
연결 정의
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' => '',
),
),
);
개요
사용할 연결을 지정하려면 간단히 connection()
메소드 를 실행하십시오.
Schema::connection('mysql2')->create('some_table', function($table)
{
$table->increments('id'):
});
쿼리 작성기
$users = DB::connection('mysql2')->select(...);
웅변
Set the $connection
variable in your model
class SomeModel extends Eloquent {
protected $connection = 'mysql2';
}
You can also define the connection at runtime via the setConnection
method or the on
static method:
class SomeController extends BaseController {
public function someMethod()
{
$someModel = new SomeModel;
$someModel->setConnection('mysql2'); // non-static method
$something = $someModel->find(1);
$something = SomeModel::on('mysql2')->find(1); // static method
return $something;
}
}
Note Be careful about attempting to build relationships with tables across databases! It is possible to do, but it can come with some caveats and depends on what database and/or database settings you have.
From Laravel Docs
Using Multiple Database Connections
When using multiple connections, you may access each connection
via the connection method on the DB
facade. The name
passed to the connection
method should correspond to one of the connections listed in your config/database.php
configuration file:
$users = DB::connection('foo')->select(...);
You may also access the raw, underlying PDO instance using the getPdo method on a connection instance:
$pdo = DB::connection()->getPdo();
Useful Links
- Laravel 5 multiple database connection FROM
laracasts.com
- Connect multiple databases in laravel FROM
tutsnare.com
- Multiple DB Connections in Laravel FROM
fideloper.com
In Laravel 5.1, you specify the connection:
$users = DB::connection('foo')->select(...);
Default, Laravel uses the default connection. It is simple, isn't it?
Read more here: http://laravel.com/docs/5.1/database#accessing-connections
Actually, DB::connection('name')->select(..)
doesnt work for me, because 'name' has to be in double quotes: "name"
Still, the select query is executed on my default connection. Still trying to figure out, how to convince Laravel to work the way it is intended: change the connection.
Edit: I figured it out. After debugging Laravels DatabaseManager it turned out my database.php (config file) (inside $this->app) was wrong. In the section "connections" I had stuff like "database" with values of the one i copied it from. In clear terms, instead of
env('DB_DATABASE', 'name')
I needed to place something like
'myNewName'
since all connections were listed with the same values for the database, username, password, etc. which of course makes little sense if I want to access at least another database name
Therefore, every time I wanted to select something from another database I always ended up in my default database
Laravel has inbuilt support for multiple database systems, you need to provide connection details in config/database.php file
return [
'default' => env('DB_CONNECTION', 'mysql'),
'connections' => [
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
'engine' => null,
],
'mysqlOne' => [
'driver' => 'mysql',
'host' => env('DB_HOST_ONE', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE_ONE', 'forge'),
'username' => env('DB_USERNAME_ONE', 'forge'),
'password' => env('DB_PASSWORD_ONE', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
'engine' => null,
],
];
Once you have this you can create two base model class for each connection and define the connection name in those models
//BaseModel.php
protected $connection = 'mysql';
//BaseModelOne.php
protected $connection = 'mysqlOne';
You can extend these models to create more models for tables in each DB.
참고URL : https://stackoverflow.com/questions/31847054/how-to-use-multiple-databases-in-laravel
'Programing' 카테고리의 다른 글
DirectX SDK (2010 년 6 월) 설치 문제 : 오류 코드 S1023 (0) | 2020.05.22 |
---|---|
R에서 같은 줄에 문자열 및 변수 내용 인쇄 (0) | 2020.05.22 |
함수에서 여러 번 반환 (0) | 2020.05.21 |
사전을 목록으로 변환 하시겠습니까? (0) | 2020.05.21 |
당신이 경험 한 최악의 실제 매크로 / 전 처리기 남용은 무엇입니까? (0) | 2020.05.21 |