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

时间:2014-04-21 14:16:26

标签: php database laravel-4

我一直在关注指南here并完成所有设置。该指南解释了如何获取子域并使用它来连接到正确的数据库。每个租户都有自己的数据库,并且还有一个主_admin数据库。此_admin数据库将具有带子域列的租户表。 每次检查子域对租户表时都会运行一个过滤器。问题出现之前,数据库配置文件未设置为主_admin数据库,其中包含租户表,但设置为mysql_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)

1 个答案:

答案 0 :(得分:1)

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

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

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