我想要的是基于子域访问单独的数据库。所有其他设置保持不变:用户名,密码等。只需要更改数据库名称。
我将此添加到database.php文件中
'subdomain' => [
'driver' => 'mysql',
'host' => '',
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
我还创建了中间件
`$subdomain = $request->route()->account;
$customer = Customer::where( 'sub_domain', $subdomain )->first();
if( ! $customer ) {
// account not found, do something else
} else {
Config::set('database.connections.subdomain.host', 'testdomain');
}
return $next($request);`
这是在route.php
Route::group(['domain' => $domain, 'middleware' => 'subdomain'],function () {});
在模型中使用protected $connection = 'subdomain';
在.env中我使用默认数据库来检查客户数据库名称
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=ispsoft
DB_USERNAME=root
DB_PASSWORD=
我有子域用户数据库名称。但没有连接的子域数据库我没有从子域数据库获取值
尝试根据子域设置模型的$table
。如果它只是一个不同的mysql架构,你应该能够做到这样的事情:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Widget extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
$subdomain = Config::get('database.connections.subdomain.host', 'testdomain');
protected $table = $subdomian.'.widgets';
}