在Laravel中的多个数据库中使用事件和监听器

时间:2017-08-01 06:05:16

标签: database laravel event-listener

我有一些主数据库和一些表,每个客户端都有不同的数据库。使用事件和监听器我在哪里指定要使用的连接字符串。对于模型和控制器我使用了Config:set动态更改我的连接字符串对于一个请求。我在侦听器句柄方法中添加了相同的内容,但是这不起作用,并且事件显示为失败。

提前致谢。 监听器方法。

public function handle(ApplicationAssociated $event)
{   
    echo "Hi";
    $client_id=$event->client_id;
    echo 'hiii'.$client_id;
    $dbconnections=DBConnection::where('client_id',$client_id)->get();
    if($client_id>0)
    {

        foreach($dbconnections as $dbconnection)
        {
            echo "in if the db name is".$dbconnection->mysql_database;
            echo "break";
            if($dbconnection->mysql_password==NULL)
             {
                 $password="";
             }
             else
             {
                 $password=$dbconnection->password;
             }
             \Config::set([
                 'database.connections.mysql1.host' => $dbconnection->mysql_host,
                 'database.connections.mysql1.database' => $dbconnection->mysql_database,
                 'database.connections.mysql1.username' => $dbconnection->mysql_username,
                 'database.connections.mysql1.password' => $password,
            ]);    
        }

    }

    echo \Config::get('database.connections.mysql1.database');

    Application::where('id',21)
    ->update(['name' =>'Testing eventing']);
    echo "LAST";

}

1 个答案:

答案 0 :(得分:0)

尝试一下。

config / database.php

    'mysql2' => [
        'driver'         => 'mysql',
        'host'           => env('DB_HOST', '127.0.0.1'),
        'port'           => env('DB_PORT', '3306'),
        'database'       => env('DB_DATABASE2', 'forge'),
        'username'       => env('DB_USERNAME2', 'forge'),
        'password'       => env('DB_PASSWORD2', ''),
        'unix_socket'    => env('DB_SOCKET', ''),
        'charset'        => 'utf8mb4',
        'collation'      => 'utf8mb4_unicode_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'),
        ]) : [],
    ],

.env文件

DB_DATABASE2=ichuztowork
DB_USERNAME2=root
DB_PASSWORD2=

您可以在应用程序中的任何地方以这种方式设置连接字符串

$user = (new \App\User(['name'=>'My Name', 'email'=>'myEmail@email.com']))- 
>setConnection('foreignDB');
$user->save();

// or if you don't need to use the model, then just
(new \App\User(['name'=>'My Name', 'email'=>'myEmail@email.com']))- 
>setConnection('foreignDB')->save();