在多租户环境下使用Laravel tinker

3
我正在使用Laravel-5.2开发一个多租户应用程序。每个租户都有一个独立的数据库和子域名。我使用他们的子域名来检测租户。
我已经设置了模型Tenant和DatabaseConnection,其中Tenant hasOne DatabaseConnection,DatabaseConnection belongsTo Tenant。通过BeforeMiddleware动态设置了租户的DB连接。这些工作得非常好。
现在我想为租户使用artisan tinker。但是如果我运行php artisan tinker,它会连接到.env文件中存在DB凭据的Tenant。
因此,我正在尝试制作相同的控制台命令。以下是我目前实现的内容。
class ClientTinker extends Command {

    protected $name = 'cdb:tinker';

    public function fire()
    {
        // get the subdomain
        $subdomain = $this->argument('subdomain');

        // get the client
        $client = Tenant::whereSubdomain($subdomain)->first();

        $connection = $client->databaseConnection();
        // $connection contains the database server, database name, user name, and password.
        // dynamically set connections here. *How?*
        ...

        // *I need to call tinker here. How?* 
    }

    protected function getArguments()
    {
        return [
            ['subdomain', InputArgument::REQUIRED, 'Subdomain of the tenant.'],
        ];
    }

那我如何为特定租户设置数据库连接,以及如何运行tinker?


http://stackoverflow.com/questions/31281669/how-do-i-connect-to-different-databases-at-run-time - Tony Vincent
你是否正在尝试创建一个控制台命令,以便在特定租户中进行“tinker”操作? - linuxartisan
是的。这样我就不必在运行“tinker”之前不断更改“.env”文件中的DB凭据了。 - user6737580
1个回答

2

fire()函数中获取$connection变量后,执行以下步骤

DB::purge('mysql');

Config::set('database.connections.mysql.host', $connection->server);
Config::set('database.connections.mysql.database', $connection->database);
Config::set('database.connections.mysql.username', $connection->username);
Config::set('database.connections.mysql.password', $connection->password);
// I am assuming the variable names in $connection object here, as you have not specified them in your question.

Artisan::call('tinker');

看看这个对你是否有效。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接