CodeIgniter Forums
CI4 .env file connecting to multiple databases not working - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: Installation & Setup (https://forum.codeigniter.com/forumdisplay.php?fid=9)
+--- Thread: CI4 .env file connecting to multiple databases not working (/showthread.php?tid=78514)



CI4 .env file connecting to multiple databases not working - Kaosweaver - 02-01-2021

I have four databases I wish to connect to, like so:

Code:
database.default.hostname = 127.0.0.1
database.default.username = something1
database.default.password = somepass1
database.default.database = somedatabase1
database.default.DBDriver = MySQLi

database.second.hostname = 127.0.0.1
database.second.username = something1
database.second.password = somepass1
database.second.database = somedatabase2
database.second.DBDriver = MySQLi

(and so on to database.fourth...)

When I had just one (default) it worked, when I added the other three, it stopped. Any clues?


RE: CI4 .env file connecting to multiple databases not working - kenjis - 02-02-2021

You need to add the property `second` in app/Config/Database.php.

https://github.com/codeigniter4/CodeIgniter4/blob/87327d32e43e9fcfdf9bbee197a4b5743ece0258/app/Config/Database.php#L33


RE: CI4 .env file connecting to multiple databases not working - Kaosweaver - 02-02-2021

(02-02-2021, 12:48 AM)kenjis Wrote: You need to add the property `second` in app/Config/Database.php.

https://github.com/codeigniter4/CodeIgniter4/blob/87327d32e43e9fcfdf9bbee197a4b5743ece0258/app/Config/Database.php#L33

Thank you, that worked perfectly.

That should be documented in the https://codeigniter.com/user_guide/database/configuration.html#configuring-with-env-file page of the docs as it wasn't said that is what is needed.


RE: CI4 .env file connecting to multiple databases not working - gosocial2 - 02-02-2021

I've had a similar problem where I was able to define connection to the second database, but the convenience model methods (such as $theModel->findAll() ) not working on models based on the 2nd database.

Consider:


Code:
$modelBasedOnDb1 = model('model1'); // using $db1
$results1 = $modelBasedOnDb1->findAll(); // works fine

$modelBasedOnDb2 = new ModelBasedOnDb2();
$modelBasedOnDb2->db = $db2; // despite this
$results2 = $modelBasedOnDb2->findAll(); // produces some error like: no such table (whatevertable) on"DB 1"


(I used pseudo-names to describe the problem)

I ended up merging 3 databases in a single database because of this problem.
(Happened with CI 4.0.4 - I haven't tried again with CI 4.1.x)