在 Laravel 中使用多个数据库
Laravel 的多功能性扩展到同时处理多个数据库。请按照以下步骤完成此操作:
定义连接
使用 .env >= 5.0:
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=mysql_database DB_USERNAME=root DB_PASSWORD=secret DB_CONNECTION_PGSQL=pgsql DB_HOST_PGSQL=127.0.0.1 DB_PORT_PGSQL=5432 DB_DATABASE_PGSQL=pgsql_database DB_USERNAME_PGSQL=root DB_PASSWORD_PGSQL=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'), ], 'pgsql' => [ 'driver' => env('DB_CONNECTION_PGSQL'), 'host' => env('DB_HOST_PGSQL'), 'port' => env('DB_PORT_PGSQL'), 'database' => env('DB_DATABASE_PGSQL'), 'username' => env('DB_USERNAME_PGSQL'), 'password' => env('DB_PASSWORD_PGSQL'), ],
没有 .env
在app/config/database.php中:
return array( 'default' => 'mysql', 'connections' => array( # Primary/Default database connection 'mysql' => array( 'driver' => 'mysql', 'host' => '127.0.0.1', 'database' => 'mysql_database', 'username' => 'root', 'password' => 'secret' 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', ), # Secondary database connection 'pgsql' => [ 'driver' => 'pgsql', 'host' => 'localhost', 'port' => '5432', 'database' => 'pgsql_database', 'username' => 'root', 'password' => 'secret', 'charset' => 'utf8', 'prefix' => '', 'schema' => 'public', ] ), );
架构/迁移
使用connection()方法指定连接:
Schema::connection('pgsql')->create('some_table', function($table) { $table->increments('id'): });
或者,在顶部:
protected $connection = 'pgsql';
查询生成器
$users = DB::connection('pgsql')->select(...);
模型
(Laravel >= 5.0)
在您的中设置 $connection 变量模型:
class ModelName extends Model { // extend changed protected $connection = 'pgsql'; }
(Laravel
class SomeModel extends Eloquent { protected $connection = 'pgsql'; }
Eloquent
交易模式
DB::transaction(function () { DB::connection('mysql')->table('users')->update(['name' => 'John']); DB::connection('pgsql')->table('orders')->update(['status' => 'shipped']); });
或
DB::connection('mysql')->beginTransaction(); try { DB::connection('mysql')->table('users')->update(['name' => 'John']); DB::connection('pgsql')->beginTransaction(); DB::connection('pgsql')->table('orders')->update(['status' => 'shipped']); DB::connection('pgsql')->commit(); DB::connection('mysql')->commit(); } catch (\Exception $e) { DB::connection('mysql')->rollBack(); DB::connection('pgsql')->rollBack(); throw $e; }
您还可以在运行时指定连接:
class SomeController extends BaseController { public function someMethod() { $someModel = new SomeModel; $someModel->setConnection('pgsql'); // non-static method $something = $someModel->find(1); $something = SomeModel::on('pgsql')->find(1); // static method return $something; } }
关系注意事项
跨数据库建立关系是可能的,但需要小心处理。它依赖于所使用的特定数据库和设置。
以上是如何在 Laravel 中使用多个数据库?的详细内容。更多信息请关注PHP中文网其他相关文章!