如何仅在多租户项目的主数据库中执行作业?

How execute job only in the main database in a mult tenant project?

我有一个项目,当我的用户进行注册时,我的项目默认连接到我的主数据库 public 模式。

当用户成功注册时,我会创建一个事件来发送电子邮件,这是我的事件监听器:

class WelcomeNewCompanyListener implements ShouldQueue
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  object  $event
     * @return void
     */
    public function handle($event)
    {

        $data = array (
            'name' =>  $event->company['name'],
            'email' =>  $event->company['email'],
        );

        $beautymail = app()->make(\Snowfire\Beautymail\Beautymail::class);
        $beautymail->send('emails.welcome', $data, function($message) use ($data)
        {
            $message
                ->from('contato@44online.com.br', '44 Online')
                ->to($data['email'], $data['name'])
                ->subject('Bem vindo a 44 Online!');
        });
    }
}

当我使用与 public 相同的模式时,它工作正常,但如果我发出需要更改租户模式的请求,并且用户为每个示例创建了 ResetPasswordEvent。

我的项目在这里更改中间件中的连接:

 public function reconnect($companyInfo) {    

      DB::purge('tenant');
      Config::set('database.connections.tenant.schema', $companyInfo[0]->db_schema);
      DB::reconnect('tenant'); 
      Schema::connection('tenant')->getConnection()->reconnect();

   }

问题是当用户发出 ResetPasswordEvent 时,我的项目开始工作,但他正在从租户的数据库上进行,而不是主要 table 我尝试在句柄之后重新连接但是不工作,它坚持从租户将作业插入数据库。我该怎么办?

当我在

上处理此连接时
      DB::purge('tenant');
      Config::set('database.connections.tenant.schema', 'public');
      DB::reconnect('tenant'); 
      Schema::connection('tenant')->getConnection()->reconnect();

我得到这个失败的工作并且我没有使用任何连接

PDOException: SQLSTATE[42P01]: Undefined table: 7 ERROR:  relation "qu_users" does not exist
LINE 1: select * from "qu_users" where "qu_users"."users_id" is null...
                      ^ in 

发生了什么事?

作为作业 might/should 运行 在另一个更改默认驱动程序的进程中丢失 (无论如何,这对我来说似乎不是个好主意)

但无论如何,如果您希望您的工作使用不同的数据库。在手柄中 您需要将作业的构造函数传递给它。例如 new Job('tenant') / App::make(MyJob::class, ['connectionName' => 'tenant' ]);

这样在handle()中应该可以得到连接名,进入handle()函数后可以更改连接

一开始它需要主连接,因为您的队列工作人员可能 运行 无论如何都在该连接上。