【问题标题】:Laravel - Spatie Multi-tenancy - Getting tables to adhere to tenant databaseLaravel - Spatie 多租户 - 让表格遵守租户数据库
【发布时间】:2021-04-15 20:22:56
【问题描述】:

我正在使用 Spatie 的多租户包在我的应用程序上实现多租户。 我正在使用多数据库方法,目前我不确定我的 .env 文件中应该包含什么内容,所以我有 DB_DATABASE=landlord 指向我的房东数据库。然后我使用 DomainTenantFinder,它工作得很好。我确实有一个问题,通常当我想指示模型应该使用租户数据库连接时,我在模型中包含以下内容:

use Spatie\Multitenancy\Models\Concerns\UsesTenantConnection;

class MyModel extends Model
{
    use UsesTenantConnection;

但是.. 我有一个问题,当使用下面的数据透视表和 DB 类时(在我声明模型表的同一迁移中声明)

Schema::create('mymodel_othermodel', function (Blueprint $table) {
        $table->id();
        $table->unsignedBigInteger('mymodel_id');
        $table->unsignedBigInteger('someother_id');

        $table->foreign('mymodel_id')
            ->references('id')
            ->on('my_models');

        $table->foreign('someother_id')
            ->references('id')
            ->on('some_other_models');
    });

我写信如下:

DB::table('mymodel_somemodel')->insert([
        'mymodel_id' => $mymodel->id,
        'someother_id' => $someother->id,
    ]);

Laravel 现在尝试在房东数据库而不是租户数据库上查找 mymodel_othermodel 表(即使我使用的是正确的域)。使用 DB 类时如何获取数据透视表以尊重租户数据库?

还有一个好处:使用多租户时,我的 .env 文件中的 DB 设置下应该包含哪些内容? ;)

【问题讨论】:

    标签: php laravel multi-tenant


    【解决方案1】:

    使用 DB Facade,您应该像这样指定连接名称:

    DB::connection('tenant')->table('mymodel_othermodel')->....
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-27
      • 2014-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多