問題描述
在我的本地環境中,我使用多個租戶和 Redis(需要身份驗證).
為了服務這個項目,我正在使用 Valet.
In my local environment I am working with multiple tenants and Redis (Auth required).
To serve the project I am using Valet.
對于這種情況,我要解決這兩個連接:
For this case I am addressing these two connections:
- basic_foo (is defined in my .env)
- tenant_foo (is the one to change to during a request)
直到現在我成功地改變了連接:
Until now I successfully changed the connections like so:
config()->set('database.connections.mysql',
array_merge(
config()->get('database.connections.mysql') ,
['database' => 'tenant_foo']
);
問題
但是,現在我發現查詢構建器存在問題,保持或回退到基本連接.
Problem
However, now I am seeing an issue with the query builder, keeping or falling back to the basic connection.
運行時得到tenant_foo的預期連接結果(Redis相同)
I get the expected connection results of tenant_foo (same for Redis) when I run
dd(config()->get('database.connections.mysql'));
當我運行時,basic_foo 的結果是錯誤的但顯然是活躍的
I get the wrong but apparently active results of basic_foo when I run
dd(DB::connection()); // returns IlluminateDatabaseMySqlConnection
所以總而言之,應用程序將返回這個 IlluminateDatabaseQueryException
So all in all the app will return this IlluminateDatabaseQueryException
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'basic_foo.table_bar' doesn't exist...
應該在哪里搜索
'tenant_foo.table_bar'
還沒有解決問題的事情
- 重啟Redis
- 重新安裝Redis
- php 工匠配置:緩存
- php artisan 緩存:清除
- php artisan route:clear
- php artisan view:clear
- php artisan 優化
- 作曲家轉儲自動加載
像下面那樣簡單地將數據庫名稱更改為 tenant_foo 是不夠的,因為配置數組保持與 basic_foo 相同.
Simply changing the database name to tenant_foo like below is not enough, as the config array remains the same of basic_foo.
DB::connection()->setDatabaseName('tenant_foo');
想法
- 我想更改 DB::connection() 的配置數組,但我不知道除了 config->set() 之外的其他方法.
- 我安裝了 Telescope 這會影響數據庫連接嗎?
- 還有其他想法嗎?
- I want to change the config-array the of DB::connection(), but I don't know another way than the config->set().
- I installed Telescope could this affect the db connection?
- Any other ideas?
Thoughts
推薦答案
要動態更改數據庫名稱,您應該使用:
To dynamically change database name you should use:
DB::disconnect();
Config::set('database.mysql.database', 'tenant_foo');
DB::reconnect();
這篇關于Laravel 6 config()->get('database.connections.mysql') 與 DB:connection() 不匹配的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!