在使用 Stancl/Tenancy
包实现 Laravel 多租户时,默认情况下,每个租户的数据库连接信息(如数据库名称、用户名、密码等)是动态生成的,但数据库连接的主机通常是固定的,通常是在 .env
文件中配置的 DB_HOST
。
如果你需要为每个租户自定义数据库连接主机,可以通过以下步骤实现:
Stancl/Tenancy
允许你通过自定义 DatabaseConfig
类来覆盖默认的数据库连接配置。你可以通过以下步骤来实现自定义数据库连接主机:
DatabaseConfig
类首先,创建一个自定义的 DatabaseConfig
类,继承自 Stancl\Tenancy\TenantDatabaseManagers\TenantDatabaseManager
。
namespace App\Tenancy\DatabaseConfig;
use Stancl\Tenancy\TenantDatabaseManagers\TenantDatabaseManager;
use Stancl\Tenancy\Contracts\TenantWithDatabase;
class CustomDatabaseConfig extends TenantDatabaseManager
{
public function getConnection(TenantWithDatabase $tenant): array
{
// 获取默认的数据库连接配置
$config = parent::getConnection($tenant);
// 自定义数据库连接主机
$config['host'] = $tenant->database_host; // 假设租户模型中有 database_host 字段
return $config;
}
}
DatabaseConfig
类接下来,你需要在 AppServiceProvider
或任何其他服务提供者中注册这个自定义的 DatabaseConfig
类。
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Stancl\Tenancy\TenantDatabaseManagers\TenantDatabaseManager;
use App\Tenancy\DatabaseConfig\CustomDatabaseConfig;
class AppServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->bind(TenantDatabaseManager::class, CustomDatabaseConfig::class);
}
}
database_host
字段确保你的租户模型(通常是 Tenant
模型)中有一个 database_host
字段,用于存储每个租户的数据库连接主机。
namespace App\Models;
use Stancl\Tenancy\Database\Models\Tenant as BaseTenant;
class Tenant extends BaseTenant
{
protected $fillable = [
'id',
'database_host',
// 其他字段...
];
}
在创建租户时,你可以通过设置 database_host
字段来指定每个租户的数据库连接主机。
use App\Models\Tenant;
$tenant = Tenant::create([
'id' => 'tenant1',
'database_host' => 'custom-host.example.com',
// 其他字段...
]);
确保在创建租户后,数据库连接主机被正确设置。你可以通过以下方式测试:
use Stancl\Tenancy\Facades\Tenancy;
Tenancy::initialize($tenant);
// 获取当前租户的数据库连接配置
$connection = config('database.connections.tenant');
dd($connection['host']); // 应该输出 'custom-host.example.com'
database_host
字段在租户模型中是可填充的(fillable
)。.env
文件中配置 DB_HOST
,而不需要自定义 DatabaseConfig
类。通过以上步骤,你可以为每个租户自定义数据库连接主机,从而实现更灵活的多租户数据库管理。