Reputation: 488
I have a question about handling multiple DB connections in Laravel 4.1. Say I have one DB host with 3 DBs on that host
eg:
'mysql' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'DB_1',
'username' => $_ENV['MYSQL_USER'],
'password' => $_ENV['MYSQL_PASS'],
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
'mysql2' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'DB_2',
'username' => $_ENV['MYSQL_USER'],
'password' => $_ENV['MYSQL_PASS'],
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
'mysql3' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'DB_3',
'username' => $_ENV['MYSQL_USER'],
'password' => $_ENV['MYSQL_PASS'],
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
Should I be making 3 different connections to those DBs?
Or should I simply have one connection and in each model specify the table name to something like:
public $table = "DB_2.table_name";
The reason I ask, is that I have noticed that I it is easier to exhaust the database connections as it creates a new DB connection when ever it needs to connect to a different database.
I know both will work, but I'm interested in what is considered to be "best practice" in this sort of situation.
Thanks in advance for the feedback.
Cheers.
Upvotes: 5
Views: 2037
Reputation: 1478
This code made the trick for me when I needed.
Config::set('database.default', 'database_name');
In your case, replace the database_name with the ones you may need. I call it in the controller each time I see a need to make the switch. Before a query, for exemple.
I don't know if is the best way ever to do it, but it worked for me and I thought it worth sharing! =D
Upvotes: 0
Reputation: 41508
Specify to the table, not the DB implementation.
I'm not a big fan of the 'feature' that allows cross DB querying on MySQL between DB's on the same server. This is what would allow the thing you mention.
table_name_test
to test your code or a db modification, you'll have to modify all your tables tames in your code each time you jump between db's vs. just editing the config file.select * from db1.foo f Join db2.bar b on b.id = f.id;
. Congratulations you just turned your 2 dbs into actually one big db that might not run outside MySQLAlso, even though you're specifying three connections, you're probably not making a connection and using all three at once... I hope. If you do use all 3 connection per request to you laravel app/site saving 2 connections is probably, micro optimization.
Upvotes: 1