laravel框架在模型中连接使用多数据库流程步骤
laravel模型中调取不同配置不同数据库的方法
1.多配置:\config\database.php
//配置1
'test1' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST1', '127.0.0.1'),
'port' => env('DB_PORT1', '3306'),
'database' => env('DB_DATABASE1', 'forge'),
'username' => env('DB_USERNAME1', 'forge'),
'password' => env('DB_PASSWORD1', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8',
'collation' => 'utf8_general_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
//配置2
'test2' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST2', '127.0.0.1'),
'port' => env('DB_PORT2', '3306'),
'database' => env('DB_DATABASE2', 'forge'),
'username' => env('DB_USERNAME2', 'forge'),
'password' => env('DB_PASSWORD2', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8',
'collation' => 'utf8_general_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
2.在model中调取不同数据数据可以使用静态方法on
//数据库test1
User::on('test1')->find(1);
//数据库test2
User::on('test2')->find(1);
相关文章