遇到作業無法連接到數據庫的問題。Laravel多租戶作業
Invalid catalog name: 1046 No database selected
我需要設置帳戶的工作,所以我有一個擴展的類,以確保該帳戶與作業一起發送,這樣我可以確保數據庫能夠連接到正確的數據庫。
<?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();
}
}
這是我現在玩的版本,變化似乎不會影響它。我基本上在構造函數中運行start
,然後確保它在作業中運行父項handle
,以便引導適當的db配置。
我在尋找的最終結果是將租戶數據庫設置爲account
,並在其運行作業時使用該數據庫進行所有查詢。