CodeIgniter Forums

Full Version: Model - read/write connections
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
A thought for Model - read/write connections:

Maybe the Model $DBGroup property could accept an array as:

PHP Code:
protected $DBGroup = [
 
   'read'  => 'slave',
 
   'write' => 'master'
]; 

And a new method like getConnection($type) to return the $db.

The builder() method could have a second param $type.

Then run the SELECTs, UPDATEs, etc according with the connection type.
That was definitely something that was in my mental roadmap, I just hadn't had an opportunity to get there yet. I think failover is currently not implemented either. Sad

It would be nice to have the system automatically give the builder the right connection. I believe there's a isWriteType() method already though that may be too late in the process for it to work for this.

I would happily accept a PR for this!
Yes. I found the isWriteType() in the \CodeIgniter\Database\Query class and also has one @todo in the \CodeIgniter\Database\BaseConnection::getConnection().

My thought is that the BaseConnection is not the place to decide if is a write or read connection because it uses a Database group. And the connection type should be based by group, because are required optimizations in the database according to the type. The failover is ok there.

So I came to the conclusion that Model would be the best place to decide which group to use. If someone wants to read/write outside the Model, just use the necessary group.

No?