Php Laravel多租户作业
遇到作业无法连接到数据库的问题Php Laravel多租户作业,php,laravel,laravel-5,multi-tenant,Php,Laravel,Laravel 5,Multi Tenant,遇到作业无法连接到数据库的问题 <?php namespace App\Jobs; use Illuminate\Support\Facades\DB; abstract class Job { protected $account; public function start() { // runs when creating the job, so the config holds the correct value $t
<?php
namespace App\Jobs;
use Illuminate\Support\Facades\DB;
abstract class Job
{
protected $account;
public function start()
{
// runs when creating the job, so the config holds the correct value
$this->account = config('database.connections.tenant.database');
}
public function handle()
{
// since the handle function runs outside of setting the job
// the database is no longer set in the config
config()->set('database.connections.tenant.database', $this->account);
// try to force it to reconnect incase it already did for some reason.
DB::reconnect();
}
}
目录名称无效:1046未选择数据库
我需要在作业中设置帐户,这样我就有一个扩展类来确保该帐户与作业一起发送,这样我就可以确保数据库可以连接到正确的数据库
<?php
namespace App\Jobs;
use Illuminate\Support\Facades\DB;
abstract class Job
{
protected $account;
public function start()
{
// runs when creating the job, so the config holds the correct value
$this->account = config('database.connections.tenant.database');
}
public function handle()
{
// since the handle function runs outside of setting the job
// the database is no longer set in the config
config()->set('database.connections.tenant.database', $this->account);
// try to force it to reconnect incase it already did for some reason.
DB::reconnect();
}
}
找到了解决这个问题的方法。这并不漂亮,但根据我所看到的情况,laravels队列并不能很好地处理这类事情
首先,我删除了handle
函数的覆盖,我真正需要的是确保运行队列所需的帐户在作业类上可用
abstract class Job
{
protected $account;
public function start()
{
// runs when creating the job, so the config holds the correct value
$this->account = config('database.connections.tenant.database');
}
}
接下来,我将开关移动到boot
方法中的AppServiceProvider
的正确租户数据库
Event::listen(JobProcessing::class, function ($event) {
if ($payload = $event->job->payload()) {
preg_match('/"account";s:[0-9]+:"(.*?)"/', $payload['data']['command'], $matches);
if (count($matches)) {
if (isset($matches[1])) {
config()->set('database.connections.tenant.database', $matches[1]);
config()->set('database.default', 'tenant');
}
}
}
});
我在这里所做的是使用一些正则表达式查看帐户的序列化对象。这里可能会有改进,但到目前为止,在测试中仍然有效。然后在确认帐户后设置正确的数据库
我必须走到这一步的原因是作业在序列化作业本身时进行查询,因此为了传递帐户,需要在序列化作业之前完成查询