在laravel中手动定义数据库连接


Manually define db connection in laravel

我一直在遵循这里的指南,并完成了所有设置。该指南解释了如何获取子域并使用它连接到正确的数据库。每个租户都有自己的数据库,还有一个master _admin数据库。此_admin数据库将有一个带有子域列的租户表。每次都会运行一个过滤器,根据租户表检查子域。问题的出现是,数据库配置文件没有设置为master _admin db,其中包括tenants表,而是设置为mysql_tenant,其中tenant是动态设置的。

我想我可以通过手动指定过滤器要连接的数据库来解决这个问题,这是我为过滤器准备的代码。

Route::filter('verifyTenant', function($route, $request) 
{
$host = $request->getHost();
$parts = explode('.', $host);
$subdomain = $parts[0];
# Ping DB for tenant match. Note that my Tenant model directs laravel to ping the tenant table in the master db to verify tenant
$tenant = Tenant::where('subdomain', '=', $subdomain)->first();

# If tenant database exists but tenant not in master db, redirect to homepage
if ($tenant == null) return Redirect::to('http://www.'.Config::get('app.domain'));
});

我需要更改的行是:

$tenant = Tenant::where('subdomain', '=', $subdomain)->first();

我尝试过做以下操作,但出现错误:

$tenant = DB::connection('mysql')->Tenant::where('subdomain', '=', $subdomain)->first();

我得到的错误是:

Symfony ' Component ' Debug ' Exception ' FatalErrorException
syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM)

使用on()方法指定连接:

$tenant = Tenant::on('db_connection')->where('subdomain', '=', $subdomain)->first();

将数据库连接的名称替换为db_connection(在您的示例中为mysql)。