CodeIgniter Forums
Model - read/write connections - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Feature Requests (https://forum.codeigniter.com/forumdisplay.php?fid=29)
+--- Thread: Model - read/write connections (/showthread.php?tid=72008)



Model - read/write connections - natanfelles - 10-24-2018

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.


RE: Model - read/write connections - kilishan - 10-24-2018

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!


RE: Model - read/write connections - natanfelles - 10-24-2018

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?