沃梦达 / 编程问答 / php问题 / 正文

laravel中动态连接多个数据库

Connect multiple databases dynamically in laravel(laravel中动态连接多个数据库)

本文介绍了laravel中动态连接多个数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个需要连接 2 个数据库的应用程序.第一个是静态的,另一个是动态的.config/database.php 就像

I'm building an application which requires connecting 2 database. first one is static and another one is dynamic. config/database.php is like

'mysql' => 
array (
  'driver' => 'mysql',
  'host' => '127.0.0.1',
  'port' => '3306',
  'database' => 'blog',
  'username' => 'root',
  'password' => '',
  'unix_socket' => '',
  'charset' => 'utf8mb4',
  'collation' => 'utf8mb4_unicode_ci',
  'prefix' => '',
  'strict' => true,
  'engine' => NULL,
),
'business2' => 
array (
  'driver' => 'mysql',
  'host' => '127.0.0.1',
  'port' => '3306',
  'database' => 'blog2',
  'username' => 'root',
  'password' => '',
  'unix_socket' => '',
  'charset' => 'utf8mb4',
  'collation' => 'utf8mb4_unicode_ci',
  'prefix' => '',
  'strict' => true,
  'engine' => NULL,
),

和型号代码是一样的

Class  TableNewData extends Model
{
    protected $connection = 'business3';
    protected $table = 'table2_data';
    public function getData()
    {
        return $this->get()->toArray();
    }
}

如果我提供静态连接详细信息,我可以连接多个数据库,但如果我提供动态连接详细信息,我将无法连接数据库

I am able to connect multiple databases if I give static connection details but I am unable to connect database if I give dynamic connection details like

 $connection = Session::get()->connection;  

$connection=$_SESSION('connection');

在不影响应用程序性能的情况下动态连接多个数据库的最佳方法是什么?

What is the best way to connect multiple databases dynamically without effecting performance of application?

推荐答案

在运行时更改连接的一种方法是通过配置设置值:

One way of changing the connection at runtime is to set the values via the config:

config(['database.connections.mysql' => [
    'driver'    => 'mysql',
    'host'      => env('DB_HOST', 'localhost'),
    'database'  => env('DB_DATABASE', 'my_database'),
    'username'  => env('DB_USERNAME', 'my_user'),
    'password'  => env('DB_PASSWORD', 'my_password'),
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
    'strict'    => false,
]]);

这可以应用在中间件中,例如在租户数据库之间动态切换.

This can be applied in a middleware to dynamically switch between tenant databases, for example.

您还可以通过 DB 外观指定连接:

You can also specify a connection via the DB facade:

DB::connection('mysql_2')->select(...);

这篇关于laravel中动态连接多个数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:laravel中动态连接多个数据库

基础教程推荐