Yii2 sharding

Hello everyone,

Help me find a solution for sharding.

I need to transfer the "number" to the model, and depending on this "number" to change the name of the table and a connection to the database, but getDb is static function and tableName too.

I found only one solution on the git: "/axiles89/yii2-sharding", but it seems to me too difficult. Maybe you know more a cleaner solution?

(Sorry for my English)

Even if the method is static you can make the result dinamic, just override it in your model


 	* @return \yii\db\Connection the database connection used by this AR class.


    public static function getDb() {

        return <get the value from where you want>


for example:

return variable from session

return variable from a function

Same is for tableName()

Static means only that you can access a class property/method without create an instance of the object.

For example:

public static function getDb()


        return Yii::$app->get($this->dbname);


$this is not accessible in static context. So, How can I send a dynamic variable?

Seems like you should have multiple models

This solution is not suitable.

I have more than 100 tables with the same structure - and create 100 models is a bad solution :)

You can access static property/method within the same class using self::

if you access


for constant


to access static method


to access a static var

So the code is

public static function getDb()


    	return Yii::$app->get(self::dbname);


Hope it help

side note

while a constant is always static, var and method are declared as static

in order to access static var when an object is not instantiate you need to put $ before the var name (very often people miss it)

You are AMAZING!!! :) Thanks!

Perhaps someone it will be helpful:

In your model:

private static $dbname='db';

    public function setDb($db){

        self::$dbname = $db;

        return $this;


    public static function getDb()


        return Yii::$app->get(self::$dbname);


And use it something like this:

$model = Yii::createObject(Users::className());

$raw = $model->setDb('db1')->findOne(['email'=>'test@test.com']);