如何在Laravel中使用多个数据库并且根据用户更改数据库连接?
如何在Laravel中使用多个数据库并且根据用户更改数据库连接?
这个问题已经有了答案:
我想创建用户基础数据库,例如在我的系统中有两个用户A和B。我有一个主数据库和两个数据库,user_a(用户A)和user_b(用户B)。在主数据库中,我有所有用户的信息。现在我想要的是,当用户A登录系统时,它可以访问主数据库和用户_A数据库,当用户B登录时,数据库连接应该是主数据库和user_b数据库。
在 @ADyson 的建议下,这是我的答案:
我在互联网上进行了许多搜索,但是没有找到完美的解决方案。有一些博客只是解释了如何在 database.php 配置文件中创建两个或多个连接,然后在模型中使用 $connection 访问这些连接。是的,我同意这是一个好的解决方案,但是,如果我的系统有数百万用户,我不想手动在 database.php 文件中创建所有连接。
所以,我进行了一个实验,它对我有用,我想与其他开发者共享这个解决方案。
首先,我为主数据库提供了一个选择选项,该选项与所有用户的数据库名称相关(Super管理员可以在我的系统中创建用户时添加数据库名称)。
其次,我创建了一个 Middleware DatabaseSwitcher.php,并在 Kernel.php 中全局注册了此 Middleware,并在 web.php 中在 auth Middleware 之后调用此 Middleware :
(['middleware' => ['auth', 'DatabaseSwitcher']]).
下面是 Middleware 的代码。
auth = $auth; } /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { //check if user logged in if ( !$this->auth->guest() ) { //get authenticate user information $user = $this->auth->user(); //get user's database $user_db = $user->user_database; //first get default mysql connection array and use in new variable for new connection which will create dynamically.(default connection is defined in database.php config file) $dbConfig = config('database.connections.mysql'); //now use database name which is in user record; $dbConfig['database'] = $user_db; //now set a new database connection name is mysql_new in my case Config::set("database.connections.mysql_new", $dbConfig); //now set default connection which is created for the user Config::set("database.default", 'mysql_new'); //now there are two connection one for master (mysql) and other for user(mysql_new) and default connection is (mysql_new) //we can access these two connection in every models by using $connection as mentioned in Larave documentation. } return $next($request); } }
现在,我们可以通过使用标准结构或 Laravel 的方式动态地使用两个数据库连接:
protected $connection = 'mysql'; protected $connection = 'mysql_new';
所有的东西都很好,但当我们使用 unique 和 exist 时,Laravel 验证规则仍然可能存在问题。
为了解决这个问题,我使用了 unique 和 exist 规则的连接名称。例如:
//连接应该是数据库连接的名称,例如 mysql 和 mysql_new(在我的情况下)
'name' => 'required|unique:connection.users,name', 'email' => 'required|exist:connection.users,email',
我希望这能帮助所有其他想要让系统看起来像这样的开发者。很抱歉我的英语不是很好,因为我不是语法专家。