We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Horisontal sharding

Hello!

Another question about splitting data over multiple databases. Now about "Horisontal Sharding" https://docs.phalcon.io/en/latest/reference/models.html#setting-multiple-databases

I know that using function selectReadConnection I can choose right connection according to the current query conditions when I want retrieve data from the database.

But, how to choose right connection when I want put (INSERT, UPDATE) data in the database?



98.9k

The idea of 'selectReadConnection' is reduce the read load by splitting queries over several databases servers, write operations are performed in a single master database server which replicates the data to the slaves in async mode.



36.0k

Thank you for the reply! I thought that it works exactly how you explained... Do you plan to add feature such as "selectWriteConnection"?



98.9k

By simply override the getWriteConnection in a model you can dynamically change the connection used to write data:

<?php

class Robots extends Phalcon\Mvc\Model
{
    public static function getWriteConnection()
    {
        if ($this->shardKey == 'abcd') {
            return $this->getDI()->get('dbMysql1');
        }
        if ($this->shardKey == 'efgh') {
            return $this->getDI()->get('dbMysql2');
        }
        return $this->getDI()->get('dbMysql3');
    }
}


36.0k

Thank you! So, when I save object I just need check its properties and choose the right connection in the overrided function getWriteConnection. Sure there is still present problem with the null ID (INSERT case), but it's looks okay!