Laravel一个域,Session检测到多个数据库 [英] Laravel one domain, multiple database detected by Session
问题描述
我已经阅读了多个帖子/主题(例如此, 此和此),我得出的结论是,其中大多数都不符合我的要求. :
I have read several posts/topics (like this, this and this) about the subject SaaS, Multi-Tenant, etc. and I reached the conclusion that most of them does not fit my requirements:
- 我不需要多租户,因为我只会使用主域
- 我无法在.env或database.config中编写所有MySQL连接,因为它们都是动态的(至少是数据库名称)
我需要的工作流程:
- 订阅(SaaS)包含数据库名称
- 每当用户登录时,都会将其数据库名称分配给他的会话
- 对用户数据库运行所有查询
示例:
- 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
. - When the
user 1
login, the data retrieved from customers should be from databaseproject_child_one
. - When the
user 2
login, the data retrieved from customers should be from databaseproject_child_two
.
我希望将数据库名称保存在会话中,因此无需总是查询project_admin
即可知道用户应连接到哪个数据库.这是简单的部分.
I want the database name to be saved in the session so I don't need to always query the project_admin
in order to know in which database the user should connect to. This is the easy part.
推荐答案
如果您确实需要建立租户"数据库连接,则可以在中间件类中动态配置它:
If you really need to have a "tenant" database connection, then you can configure it on the fly in a middleware class:
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
连接:
You can then use this tenant
connection in database queries and models:
abstract class TenantModel extends Model
{
protected $connection = 'tenant';
}
class Widget extends TenantModel
{
protected $table = 'widgets';
}
这篇关于Laravel一个域,Session检测到多个数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!