問題描述
我需要在運行時更改 Laravel 5 數據庫連接.
I need to change laravel 5 database connection in run time.
你有什么想法嗎?
請分享給我.
謝謝.
推薦答案
更新:這個答案來自 2015 年!我已經很多年沒有使用 Laravel 了,我也沒有掌握最新的最佳實踐.這個答案不斷得到支持,所以我認為它有效,但請謹慎行事.
Update: This answer is from 2015! I haven't used Laravel in years and I am not up to date with the latest best practices. This answer keeps getting upvoted so I suppose it works but please proceed with caution.
好吧,我對此的直接回答是:不要.您可以通過更改數據模型和使用一些更高級的關系來完成任務.不知道你想做什么很難說,但在我看來,這通常是個壞主意,特別是如果你打算使用 eloquent 模型等等
Well, my immediate answer to this is: don't. Chances are that you can accomplish your task by changing your data model and working with some more advanced relationships. It's hard to tell without knowing what you want to do but it seems to me like a bad idea in general, specially if you're planning on using eloquent models and so on
也就是說,在某些情況下,您確實需要更改另一個數據庫中的數據或執行一些原始查詢,您可以使用 DB::connection()
方法.類似的東西:
That said, in some scenario where you really need to alter data in another database or execute some raw query you can use the DB::connection()
method. Something like:
$data = DB::connection('another_connection')->select(...);
您可以在 database.php
文件中指定 another_connection
變量.像這樣:
You can specify that another_connection
variable at your database.php
file. Like this:
<?php
return array(
'default' => 'mysql',
'connections' => array(
# Your regular connection
'mysql' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'database',
'username' => 'user',
'password' => 'password'
'charset' => 'utf8',
),
# Your new connection
'another_connection' => array(
'driver' => 'mysql',
'host' => 'another_host',
'database' => 'another_db',
'username' => 'user1',
'password' => 'password1'
'charset' => 'utf8',
),
),
);
您甚至可以使用 protected $connection = 'another_connection'; 為每個 eloquent 模型指定一個連接
也可以為每個在運行時創建/查詢的模型實例指定一個連接
You can even specify a connection for each eloquent model using protected $connection = 'another_connection';
also you can specify a connection for each model instance created/queried at run time
$user = new User;
$user->setConnection('another_connection');
$user1 = $user->find(1);
但話說回來,我個人認為這不是一個好主意,而且在我看來,隨著應用程序復雜性的增加,一切都會變得混亂并很快崩潰.
But then again, I personally don't think this is a good idea and it seems to me that everything can get messy and fall apart very quickly as your application grows in complexity.
這篇關于laravel 更改數據庫連接運行時的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!