这是我在@ADyson 建议后的回答
我在 INTERNET 上进行了很多搜索,但没有找到任何完美的解决方案。
有一些博客只解释了创建两个或多个连接 database.php 配置文件,然后使用 $connection 在模型中访问这些连接。
是的,我同意这是一个很好的解决方案,但是,如果我的系统中有数百万用户,我不想手动在 database.php 文件上创建所有连接。
所以我做了一个实验,它对我有用,我想把这个解决方案分享给所有其他开发人员。
首先我在主数据库中为所有用户的数据库名称提供一个选项(超级管理员可以在超级管理员创建用户后添加数据库名称,就像在我的系统中一样)
其次,我创建了一个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 并且存在时,Laravel 验证规则仍然可能存在问题。
为了克服这个问题,我使用了唯一且存在规则的连接名称。
例如
//connection 应该是数据库连接的名称,例如 mysql 和 mysql_new(在我的例子中)
'name' => 'required|unique:connection.users,name',
'email' => 'required|exist:connection.users,email',
我希望它可以帮助所有其他想要看起来像这样的系统的开发人员。
对不起我的英语,因为我不是语法专家。