这完全取决于您如何处理多个连接。我从事过类似的需求项目。
租户模型抽象类
<?php
namespace App\Models\Abstracts;
use App\Models\Abstracts\AbstractBaseModel;
use App\Models\Picklist\PicklistValue;
class TenantAbstractBaseModel extends AbstractBaseModel
{
function __construct(array $attributes = array())
{
parent::__construct($attributes);
if ( ! is_null(app('tenant.context')->getConnectionName())) {
$this->setConnection(app('tenant.context')->getConnectionName());
}
//todo; should be dynamic
if (is_null(app('tenant.context')->getConnectionName())
&& app()->runningInConsole()
) {
//todo; need to resolve database connection through terminal and application.
//dd(config('tenant.tenant_connection'));
//$this->setConnection(config('tenant.tenant_connection'));
}
}
}
登录后的租户设置
$connection = config('tenant.tenant_connection');
//config()->set('database.default', config('tenant.tenant_connection'));
app('tenant.context')->setConnectionName($connection);
app('tenant.context')->setTenantId($company_id);
//$database = config('database.connections.' . $connection . '.database') . $company_id;
$company_system_name
= $this->auth->user()->company->system_name;
config()->set('database.connections.'.$connection.'.database',
$company_system_name);
//config()->set('database.connections.' . $connection . '.database', $database);
config()->set('database.default', $connection);
数据库连接
<?php
namespace App\Tenancy\Tenant;
use Config;
use DB;
use App\Tenancy\Exceptions\TenantDatabaseException;
use App\Tenancy\Models\Tenant;
/**
* Class DatabaseConnection
*
* Helps with tenant database connections
*/
class DatabaseConnection
{
/**
* See the multi-tenant configuration file. Configuration set
* to use separate databases.
*/
const TENANT_MODE_SEPARATE_DATABASE = 'database';
/**
* See the multi-tenant configuration file. Configuration set
* to use prefixed table in same database.
*/
const TENANT_MODE_TABLE_PREFIX = 'prefix';
/**
* Current active global tenant connection.
*
* @var string
*/
protected static $current;
/**
* @var string
*/
public $name;
/**
* @var Tenant
*/
protected $tenant;
/**
* @var \Illuminate\Database\Connection
*/
protected $connection;
public function __construct(Tenant $tenant)
{
$this->tenant = $tenant;
$this->name = "tenant.{$this->tenant->hash_id}";
$this->setup();
}
/**
* Sets the tenant database connection.
*/
public function setup()
{
Config::set("database.connections.{$this->name}", $this->config());
}
/**
* Generic configuration for tenant.
*
* @return array
*/
protected function config()
{
$clone = Config::get(sprintf('database.connections.%s',
static::tenantConnectionName()));
$clone['database'] = $this->tenant->system_name;
return $clone;
}
/**
* Central getter for system connection name.
*
* @return string
*/
public static function systemConnectionName()
{
return Config::get('tenant.master_connection', 'mysql');
}
/**
* Checks whether current connection is set as global tenant connection.
*
* @return bool
*/
public function isCurrent()
{
return $this->name === static::getCurrent();
}
/**
* Loads the currently set global tenant connection name.
*
* @return string
*/
public static function getCurrent()
{
return static::$current;
}
/**
* Sets current global tenant connection.
*/
public function setCurrent()
{
static::$current = $this->name;
Config::set(sprintf('database.connections.%s',
static::tenantConnectionName()), $this->config());
DB::purge(static::tenantConnectionName());
}
/**
* Central getter for tenant connection name.
*
* @return string
*/
public static function tenantConnectionName()
{
return Config::get('tenant.tenant_connection', 'tenant_mysql');
}
/**
* Loads connection for this database.
*
* @return \Illuminate\Database\Connection
*/
public function get()
{
if (is_null($this->connection)) {
$this->setup();
$this->connection = DB::connection($this->name);
}
return $this->connection;
}
/**
* @return bool
*/
public function create()
{
$clone = $this->config();
return DB::connection(static::systemConnectionName())
->transaction(function () use ($clone) {
if ( ! DB::connection(static::systemConnectionName())
->statement("create database if not exists `{$clone['database']}`")
) {
throw new TenantDatabaseException("Could not create database {$clone['database']}");
}
if ( ! DB::connection(static::systemConnectionName())
->statement("grant all on `{$clone['database']}`.* to `{$clone['username']}`@'{$clone['host']}' identified by '{$clone['password']}'")
) {
throw new TenantDatabaseException("Could not create or grant privileges to user {$clone['username']} for {$clone['database']}");
}
return true;
});
}
/**
* @throws \Exception
*
* @return bool
*/
public function delete()
{
$clone = $this->config();
return DB::connection(static::systemConnectionName())
->transaction(function () use ($clone) {
if ( ! DB::connection(static::systemConnectionName())
->statement("revoke all on `{$clone['database']}`.* from `{$clone['username']}`@'{$clone['host']}'")
) {
throw new TenantDatabaseException("Could not revoke privileges to user {$clone['username']} for {$clone['database']}");
}
if ( ! DB::connection(static::systemConnectionName())
->statement("drop database `{$clone['database']}`")
) {
throw new TenantDatabaseException("Could not drop database {$clone['database']}");
}
return true;
});
}
}
*TenantContextSession *
<?php
namespace App\Repositories\Tenant;
use App\Repositories\Tenant\TenantContextRepositoryContract;
/**
* Description of TenantContextSession
*
* @author safoor
*/
class TenantContextSession implements TenantContextRepositoryContract
{
// public function __construct() {
// $this->clearTenantSession();
// }
/**
* Sets the connection name for the actual context
* this tenant
* @param $name
* @return mixed
*/
public function setConnectionName($name)
{
if (session()->has('tenant_connection')) {
session()->set('tenant_connection', '');
}
session()->put('tenant_connection', $name);
}
/**
* Get the name of the current connection in context
* @return mixed
*/
public function getConnectionName()
{
return session()->get('tenant_connection');
}
/**
* Sets the id value filter data in the current context
* @param $id
* @return mixed
*/
public function setTenantId($id)
{
if (session()->has('tenant_id')) {
session()->set('tenant_id', '');
}
session()->put('tenant_id', $id);
}
/**
*
* @return mixed
*/
public function getTenantId()
{
return session()->get('tenant_id');
}
public function clearTenantSession()
{
session()->flush();
session()->set('tenant_id', '');
session()->set('tenant_connection', '');
}
}
我希望这将有助于您的场景,我已尝试提及我们必须涵盖的所有方面,但如果仍有一些令人困惑的地方需要我的解释,请告诉我。