我想创建用户基础数据库,例如在我的系统中有两个用户A和B。我有一个主数据库和两个数据库user_a(用于用户A)和user_b(用于用户B)。在主数据库中,我拥有所有用户信息。现在我想要的是,当用户A登录系统时,它访问master数据库和user_a数据库,而当用户B登录数据库时,连接应该是master数据库和user_b数据库。
最佳答案
这是我在@ADyson建议后的回答
我在互联网上进行了很多搜索,但没有找到任何完美的解决方案。
有一些博客只解释了创建两个或多个连接database.php配置文件,然后使用$connection在模型中访问这些连接。
是的,我同意这是一个很好的解决方案,但是,如果我的系统中有数百万用户,我不想在 database.php
上创建所有连接怎么办?手动归档。
所以我做了一个实验,它对我有用,我想与所有其他开发人员分享这个解决方案。
首先,我在主数据库中为所有用户的数据库名称提供一个选项( super 管理员可以在 super 管理员创建用户后添加数据库名称,就像在我的系统中一样)
第二个我创建了一个 Middleware DatabaseSwitcher.php
并在Kernel.php
中全局注册了该中间件并在 web.php
中的 auth 中间件之后调用此中间件:
(['middleware' => ['auth', 'DatabaseSwitcher']]).
以下是中间件的代码。
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
use Config; //to get configuration data
class DatabaseSwitcher {
/**
* The Guard implementation.
*
* @var Guard
*/
protected $auth;
/**
* Create a new filter instance.
*
* @param Guard $auth
* @return void
*/
public function __construct(Guard $auth)
{
$this->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 验证规则仍然可能存在问题。
为了解决这个问题,我使用了具有唯一和存在规则的连接名称。 例如 //connection 应该是数据库连接的名称,如 mysql 和 mysql_new (在我的例子中)
'name' => 'required|unique:connection.users,name',
'email' => 'required|exist:connection.users,email',
我希望它能帮助所有其他想要将系统看起来像这样的开发人员。 抱歉我的英语不好,因为我不是语法专家。
关于php - 如何在 Laravel 中使用多个数据库并随用户更改数据库连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57412363/