Orchestral / tenanti多数据库

时间:2016-08-03 22:22:17

标签: laravel multi-tenant multi-database

我为许多租户构建了一个应用程序,每个租户都拥有自己的数据库。数据库的名称与租户ID相同。(id存在于五个数字中)。验证后,用户应与自己的数据库连接并重定向到他的仪表板。

我尝试使用以下代码将用户与他的数据库连接起来,我将其放入Authenticate.php中

if (!Auth::guest() && Auth::user()->tenant) {
        $user = Auth::id();
        Tenanti::driver('user')->asDefaultDatabase($user, 'users_{id}');
        Config::set('database.connections.mysql.database', 'user_'.$user); 
    }

if语句在主数据库中检查登录用户是否为租户(布尔值)。

config / database.php包含以下代码:

 'tenants' => [
        'user_1' => [
            'driver'    => 'mysql',
            'host'      => 'localhost',     // for user with id=1
            'database'  => '86097',     // for user with id=1
            'username'  => 'root', // for user with id=1
            'password'  => 'root', // for user with id=1
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'strict'    => false,
            ],
        ],

AppServiceProvider:

<?php namespace App\Providers;

use Orchestra\Support\Facades\Tenanti;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
{
    Tenanti::setupMultiDatabase('tenants', function (User $entity, array $template) {
        $template['database'] = "user_{$entity->getKey()}";

        return $template;
    });
}
}
?>

我没有收到错误,但连接没有改变。用户数据库为空,因此当我使用user_id = 1登录时,我不应该看到任何数据。在此先感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

配置应为:

'tenants' => [
    'driver'    => 'mysql',
    'host'      => 'localhost',     // for user with id=1
    'database'  => '86097',     // for user with id=1
    'username'  => 'root', // for user with id=1
    'password'  => 'root', // for user with id=1
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
    'strict'    => false,
],

除此之外,请将Tenanti::setupMultiDatabase()替换为Tenanti::connection()(我们已弃用旧方法)。

并更改以下内容:

Tenanti :: driver(&#39; user&#39;) - &gt; asDefaultConnection(Auth :: user(),&#39; tenants_ {id}&#39;);

显然,如果您想使用users_{id},则需要将所有tenants替换为users

相关问题