插件窝 干货文章 如何在 Laravel 多租户扩展 stancl/tenancy 中自定义租户数据库主机?

如何在 Laravel 多租户扩展 stancl/tenancy 中自定义租户数据库主机?

数据库 租户 Tenant 定义 887    来源:    2025-03-12

在 Laravel 中使用 stancl/tenancy 扩展实现多租户时,默认情况下,每个租户的数据库连接信息(如数据库名称、用户名、密码等)是动态生成的。如果你想自定义租户的数据库主机(即数据库服务器地址),可以通过以下步骤实现。

1. 自定义数据库连接配置

stancl/tenancy 允许你通过自定义数据库连接配置来覆盖默认的数据库连接设置。你可以在租户创建或更新时,动态设置数据库主机。

2. 修改 Tenant 模型

首先,你需要在 Tenant 模型中添加一个字段来存储自定义的数据库主机。你可以通过迁移文件添加这个字段:

Schema::table('tenants', function (Blueprint $table) {
    $table->string('database_host')->nullable();
});

3. 自定义数据库连接

接下来,你需要在 Tenant 模型中自定义数据库连接。你可以通过覆盖 configure 方法来实现这一点:

use Stancl\Tenancy\Database\Models\Tenant as BaseTenant;

class Tenant extends BaseTenant
{
    public function configure()
    {
        parent::configure();

        // 获取自定义的数据库主机
        $databaseHost = $this->database_host;

        // 如果自定义了数据库主机,则覆盖默认的数据库连接配置
        if ($databaseHost) {
            config(['database.connections.tenant.host' => $databaseHost]);
        }
    }
}

4. 在创建租户时设置数据库主机

当你创建或更新租户时,可以设置 database_host 字段:

$tenant = Tenant::create([
    'id' => 'tenant1',
    'database_host' => 'custom-db-host.example.com',
    // 其他租户字段...
]);

$tenant->configure();

5. 使用自定义数据库连接

在租户的上下文中,Laravel 会自动使用你自定义的数据库连接配置。你可以在租户的代码中正常使用数据库操作,而不需要手动切换连接。

6. 注意事项

  • 确保你的数据库服务器允许从应用程序服务器访问。
  • 如果你使用的是共享数据库服务器,确保每个租户的数据库名称是唯一的。
  • 如果你需要动态切换数据库主机,确保在租户切换时正确配置数据库连接。

7. 示例代码

以下是一个完整的示例代码,展示了如何在 stancl/tenancy 中自定义租户数据库主机:

use Stancl\Tenancy\Database\Models\Tenant as BaseTenant;

class Tenant extends BaseTenant
{
    public function configure()
    {
        parent::configure();

        // 获取自定义的数据库主机
        $databaseHost = $this->database_host;

        // 如果自定义了数据库主机,则覆盖默认的数据库连接配置
        if ($databaseHost) {
            config(['database.connections.tenant.host' => $databaseHost]);
        }
    }
}

// 创建租户并设置自定义数据库主机
$tenant = Tenant::create([
    'id' => 'tenant1',
    'database_host' => 'custom-db-host.example.com',
    // 其他租户字段...
]);

$tenant->configure();

通过以上步骤,你可以在 stancl/tenancy 中自定义租户的数据库主机,并根据需要动态配置数据库连接。