使用多个数据库管理Laravel Migrations的最佳做法是什么?
答案 0 :(得分:1)
在app/config/database.php
这样做
return array(
'default' => 'mysql',
'connections' => array(
# Our primary database connection
'mysecond_database' => array(
'driver' => 'mysql',
'host' => 'host1',
'database' => 'database1',
'username' => 'user1',
'password' => 'pass1'
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
# Our secondary database connection
'myfirst_database' => array(
'driver' => 'mysql',
'host' => 'host2',
'database' => 'database2',
'username' => 'user2',
'password' => 'pass2'
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
),
);
然后在您的迁移中,您可以执行此操作
Schema::connection('mysecond_database')->create('users', function($table)
{
$table->increments('id'):
});
这将在users
连接(数据库)
mysql2
表
使用其他连接只需像这样更改
Schema::connection('myfirst_database')->create('posts', function($table)
{
$table->increments('id'):
});
如果要从一个表中检索数据
$users = DB::connection('mysecond_database')->select(...);
如果你想使用eloquent,你只需要在模型中定义连接,如下所示:
class users extends Eloquent {
protected $connection = 'mysecond_database';
}
然后你可以像这样轻松地做到这一点
$users = User::all();