我读过几篇文章/主题(例如this https://stackoverflow.com/questions/31847054/how-to-use-multiple-databases-in-laravel, this https://medium.com/teknomuslim/how-to-run-laravel-using-multiple-database-connections-d7e8dcb7ed2a and this https://laravel-tenancy.com/)关于SaaS、多租户等主题,我得出的结论是其中大多数不符合我的要求:
- 我不需要多租户,因为我只使用主域
- 我无法在 .env 或 database.config 中写入所有 MySQL 连接,因为它们都是动态的(至少是数据库的名称)
我需要的工作流程:
- 订阅 (SaaS) 包含数据库名称
- 每当用户登录时,都会将数据库名称分配给他的会话
- 对用户数据库运行所有查询
Example:
- project_admin <- Main database
--- subscriptions <- Table
------ id | db_name
------ 1 | project_child_one
------ 2 | project_child_two
--- users <- Table
------ id | subscription_id
------ 1 | 1
------ 2 | 2
- project_child_one <- Child database
--- customers <- table
- project_child_two <- Child database
--- customers <- table
- 当。。。的时候
user 1
登录后,从客户检索的数据应该来自数据库project_child_one
.
- 当。。。的时候
user 2
登录后,从客户检索的数据应该来自数据库project_child_two
.
我希望将数据库名称保存在会话中,这样我就不需要总是查询project_admin
为了知道用户应该连接到哪个数据库。这是简单的部分。
如果您确实需要有一个“租户”数据库连接,那么您可以在中间件类中动态配置它:
class ConfigureTenantConnection
{
public function handle($request, Closure $next)
{
if ($user = $request->user()) {
// Create a tenant database connection if there is an authenticated user
config([
'database.connections.tenant' => [
'driver' => 'mysql',
// I don’t know what column names you use, but…
'host' => $user->database_host,
'port' => $user->database_port,
'database' => $user->database_name,
'username' => $user->database_username,
'password' => $user->database_password,
],
]);
}
return $next($request);
}
}
然后你可以使用这个tenant
数据库查询和模型中的连接:
abstract class TenantModel extends Model
{
protected $connection = 'tenant';
}
class Widget extends TenantModel
{
protected $table = 'widgets';
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)