我在多租户系统中工作,我之前尝试过https://github.com/hyn/multi-租户包,但最终我决定使用自己的方法来实现此实现。经过大量研究和测试后,我设法构建了这段代码,但是当我执行该代码时,它告诉我未定义connect方法,在此我保留所做的工作,很可能是由于我的一些废话已经被忽略了,但是如果有人可以帮助我解决这个问题,我将不胜感激
助手:
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
if(! function_exists('conexionBD')){
/**
* Establish a tenant database connection.
*
* @param $hostname
* @param $username
* @param $password
* @param $database
*/
function conexionBD($hostname, $username, $password, $database){
DB::purge('empresa');
Config::set('database.connections.empresa.host', $hostname);
Config::set('database.connections.empresa.database', $database);
Config::set('database.connections.empresa.username', $username);
Config::set('database.connections.empresa.password', $password);
DB::reconnect('empresa');
Schema::connection('empresa')->getConnection()->reconnect();
}
}
Empresa模型:
class empresa extends Model
{
protected $fillable = [
'hostname',
'username',
'password',
'database'
];
public function ciudad() {
return $this->belongsTo('confia\ciudad');
}
public function empresaUsuario() {
return $this->hasMany('confia\empresasUsuario');
}
public function connect()
{
if (! $this->connected()) {
conexionBD(
$this->hostname,
$this->username,
$this->password,
$this->database
);
}
}
/**
* Check if the current tenant connection settings matches the company's database settings.
*
* @return bool
*/
private function connected()
{
$connection = Config::get('database.connections.empresa');
return $connection['username'] == $this->username &&
$connection['password'] == $this->password &&
$connection['database'] == $this->database;
}
}
中间件租户:
use Closure;
use confia\empresa;
class Tenant{
protected $company;
/**
* Tenant Conctructor
* @param empresa $empresa
*/
public function __construct(empresa $empresa)
{
$this->empresa = $empresa;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next) {
if (($request->session()->get('empresaId')) === null)
return redirect()->route('inicio')->withErrors(['error' => __('Por favor inicie sesión en alguna empresa antes de intentar esta acción')]);
// Get the company object with the id stored in session
$empresa= $this->empresa->find($request->session()->get('empresaId'));
// Connect and place the $company object in the view
$this->connect($empresa);
return $next($request);
}
}
在我的会话变量empresaId中,我已将公司concat的ID存储到静态字符串中,这就是给我与该公司关联的数据库名称的原因。
运行系统时,在更改租户以开始使用另一个数据库时,出现以下错误,
“调用未定义的方法app \ Http \ Middleware \ Tenant :: connect()”
有人知道我的代码丢失了,或者我做错了使多租户系统正常工作?