Switching database with Codeigniter 4 / Grocery Crud 2

Hi all,
in the past version of Codeigniter + GroceryCrud switching database was a simply as this:
$this->db = $this->load->database(‘new_db’, true);

$crud = new GroceryCrud();
$this->db = db_connect(‘new_db’);
seems not working: the accessed db remains the default one.

Any clues?

1 Like

Hi @gangio75 !!
Did you find any solution to switch the database?

Unfortunately, no.
There is a function in grocery enterprise ( setDatabaseSchema ) but it says only for PostgresSQL.

Hi @gangio75 ! Thanks for your answer!
Finally I’ve founded a solution.

You can modify the Controller/Crudcontroller file adding your model and new database connection there:

Hope it works for you too.

Sorry but I could’nt reproduce…
What does the function datos_user() do?

And in which part of it you actually connect to db?

I found a simple solution although, as is often the case with the new version of grocerycrud, it is not documented and you need to reverse engineer the sources.

Just define a new custom model, which is actually the default one.
But in this case, you can pass the correct DB connection to the constructor:
$crud->setModel(new \App\Models\GroceryCrudModel(db_connect(‘db_to_connect’)));