在 Laravel 中动态更改数据库连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46775265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:48:42  来源:igfitidea点击:

Change the Database Connection Dynamically in Laravel

phpmysqldatabaselaravelmulti-tenant

提问by tyro

I have the master database with login table and corresponding database settings for each user. On login I should dynamically change the db settings fetching from the table. I can change the db connection but this is not persisting.

我有每个用户的登录表和相应的数据库设置的主数据库。登录时,我应该动态更改从表中获取的数据库设置。我可以更改数据库连接,但这不会持久。

Config::set("database.connections.mysql", [
'driver' => 'mysql',
"host" => $usr_host,
"database" => $usr_database,
"username" => $usr_username,
"password" => $usr_password,
...
]);

edit: New database is created for each user when he/she registers with the app and thus i dont have the database connection for each user defined in the config/database.php

编辑:当他/她向应用程序注册时为每个用户创建新数据库,因此我没有在 config/database.php 中定义的每个用户的数据库连接

采纳答案by omer Farooq

Well you can use the default database for user login and have a new field for the database name. Then whenever you need to query a different database, you can just change your db connection.

那么您可以使用默认数据库进行用户登录,并为数据库名称创建一个新字段。然后每当您需要查询不同的数据库时,您只需更改数据库连接即可。

Something like this

像这样的东西

$someModel = new SomeModel;
$databaseName = "mysql2"; // Dynamically get this value from db
$someModel->setConnection($databaseName);
$something = $someModel->find(1);

You can read more about it here. http://fideloper.com/laravel-multiple-database-connections

你可以在这里读更多关于它的内容。 http://fideloper.com/laravel-multiple-database-connections

回答by Adam Kozlowski

This way you can set new parameter when it comes to database:

通过这种方式,您可以在数据库方面设置新参数:

 \Config::set('database.connections.mysql.database', $schemaName);

Remember about PURGEto persist this settings

记住PURGE要保留此设置

 DB::purge('mysql');

Cheers!

干杯!

回答by ZeroOne

you need to get the config first.. then alter the specific field then set it back..

您需要先获取配置..然后更改特定字段然后将其设置回..

$config = Config::get('database.connections.company');
$config['database'] = "company_tenant_$id";
$config['password'] = "test2123";
config()->set('database.connections.company', $config);

回答by Rusben Guzman

In laravel what you can do is create the different connections in the connections array of the file conf/database, then these connections you can use them when you are going to carry out operations in your application.

在 Laravel 中,您可以做的是在文件conf/database的连接数组中创建不同的连接,然后这些连接您可以在您要在应用程序中执行操作时使用它们。

If you use query builderor raw expresionsyou must use the connection ('name')method to perform queries, for example:

如果您使用查询构建器原始表达式,则必须使用连接 ('name')方法来执行查询,例如:

$users = DB::connection('mysql')
         ->table('users')
         ->select(...)
         ->get();

If you use eloquent you can specify the name of the connection in the model file in the connection attribute, for example:

如果使用 eloquent 可以在模型文件中的 connection 属性中指定连接的名称,例如:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The connection name for the model.
     *
     * @var string
     */
    protected $connection = 'mysql';
}

A solution to your problem could be that you have created the different types of connections according to the users in the file conf/database, and save the name of the connection that the user uses as a column in the user table, and when you go to make the queries you get the name of the connection of the user, for example:

您的问题的解决方案可能是您根据文件conf/database 中的用户创建了不同类型的连接,并将用户使用的连接名称保存为用户表中的列,并在您访问时要进行查询,您将获得用户连接的名称,例如:

$user = User::find(Auth::id());
$connection = $user->connection;

$users = DB::connection($connection)
??????????????????????->table('users')
??????????????????????->select(...)
????????????????????? ->get ();

more info:

更多信息:

https://laravel.com/docs/5.5/eloquent#eloquent-model-conventionshttps://laravel.com/docs/5.5/database#read-and-write-connections

https://laravel.com/docs/5.5/eloquent#eloquent-model-conventions https://laravel.com/docs/5.5/database#read-and-write-connections

回答by ice6

I think a good place to change the database connection place is in bootstrap/app.phpfile, use the code below:

我认为更改数据库连接位置的好地方是在bootstrap/app.php文件中,使用以下代码:

$app->afterBootstrapping(\Illuminate\Foundation\Bootstrap\LoadConfiguration::class, function ($ap) {
    // your database connection change may happens here
});

It is before ServiceProvider register and boot, so even if you use DBor Eloquentstaff in ServiceProvider, it works very well.

它是在ServiceProvider注册和启动之前,所以即使你在ServiceProvider中使用DBEloquent人员,它也能很好地工作。

回答by Noor Ahmed

After an extensive search I found it this way:

经过广泛的搜索,我是这样找到的:

Go to this file vendor\laravel\framework\src\Illuminate\Auth\Middleware\Authenticate.php

转到这个文件vendor\laravel\framework\src\Illuminate\Auth\Middleware\Authenticate.php

Go to the method: protected function authenticate($request, array $guards)and right after the method has started, paste the following code:

转到方法:protected function authenticate($request, array $guards)并在方法启动后立即粘贴以下代码:

    if(auth()->check() && !empty( auth()->user()->db_name )){

        $dynamic_db_name = auth()->user()->db_name;
        $config = \Config::get('database.connections.mysql');
        $config['database'] = $dynamic_db_name;
        $config['password'] = "Your DB Password";
        config()->set('database.connections.mysql', $config);
        \DB::purge('mysql');
    }

first we are checking if the user is logged in with

首先我们检查用户是否登录

auth()->check()

Then as you may have added db_name name or the like column table to your users table according to each user. So in the next condition, I am making sure that the db_name is available:

然后,您可能已经根据每个用户将 db_name 名称或类似的列表添加到您的用户表中。所以在下一个条件下,我确保 db_name 可用:

&& !empty( auth()->user()->db_name )

Then after execution enters the if condition I get the db_name from the user record and set the configuration according to the user database, save the config and use purge method of DB class to persist this setting. I was really stuck with it. I did not wanted to change my db connection in every class. So this is how I got it. Now I can use both Eloquent and DB without any tension anywhere. In my application I have one centeral database for login of all users and then for each organization there is a different database. So after the user has logged in, I do not need the centeral database (login database), I juse need the user/organization specific database. So this is how I got it to work.

然后执行后进入if条件我从用户记录中获取db_name并根据用户数据库设置配置,保存配置并使用DB类的清除方法来保留此设置。我真的被它困住了。我不想在每个班级都改变我的数据库连接。所以这就是我得到它的方式。现在我可以在任何地方都没有任何紧张地使用 Eloquent 和 DB。在我的应用程序中,我有一个用于登录所有用户的中央数据库,然后对于每个组织都有一个不同的数据库。所以在用户登录后,我不需要中心数据库(登录数据库),我只需要用户/组织特定的数据库。所以这就是我让它工作的方式。