duangongqiong6958 2019-04-29 18:13
浏览 46
已采纳

Laravel一个域,由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:

  1. I don't need a multi-tenant as i'm only going to use the main-domain
  2. I can't write in .env nor in database.config all my MySQL connections as they will all be dynamic (at least the name of the database)

Workflow i need:

  1. The subscriptions (SaaS) contains the database name
  2. Whenever the user login it is assigned to his session the database name
  3. Run all the queries to the user database

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
  • When the user 1 login, the data retrieved from customers should be from database project_child_one.
  • When the user 2 login, the data retrieved from customers should be from database project_child_two.

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.

  • 写回答

2条回答 默认 最新

  • dsfw2154 2019-04-29 21:04
    关注

    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);
        }
    }
    

    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';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?