【问题标题】:Orchestral/tenanti multi databaseOrchestral/tenanti 多数据库
【发布时间】:2016-08-03 22:22:17
【问题描述】:

我为许多租户构建了一个应用程序,每个租户都有自己的数据库。数据库的名称与租户 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 登录时应该看不到任何数据。提前感谢您的帮助。

【问题讨论】:

    标签: laravel multi-tenant multi-database


    【解决方案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('user')->asDefaultConnection(Auth::user(), 'tenants_{id}');

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

    【讨论】:

    • 我改变了上面的东西,但是数据仍然显示,但是租户的数据库完全是空的。除此之外,当配置仅适用于 id=1 的用户时,如何添加第二个和第三个用户?
    • 阅读github.com/orchestral/tenanti#setup-model-observer 老实说,最好先了解在单个数据库上构建多租户的概念,然后再跳过很多事情并假设一键安装可以解决所有问题。一些代码示例:github.com/crynobone/todoist/compare/master...single-databasegithub.com/crynobone/todoist/compare/… p/s:它不完整,因为我从来没有设计它来解决所有问题。
    • 我已经成功实现了一个多租户单数据库。感谢您提供有用的示例。应用程序是否需要进行大量修改才能使其成为多数据库系统?每个用户至少有四个大表(每个超过一百万行)因此我认为最好的解决方案是拥有一个多数据库系统。如果我错了,请纠正我。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-03
    相关资源
    最近更新 更多