Model with variable database

I need my model to use different databases. I want to pass $company as an argument when instatiating.

class FatFaturas extends \yii\db\ActiveRecord
{

// override of getDB method..
public static function getDb()
{
    return \common\skeyra\utils::get_client_connection($company);
}

I would like to set $company to a value when creating a new object of FatFaturas, but I can´t use $this within a static function. And the function must be static because i’m overriding a method of Activerecord.

How can I accomplish this? Any help would be appreciated.

Database connection is required before instance of model is available (you need to have connection to fetch records from database). How do you want to pass $company for FatFaturas::findOne($id)?

Thank you rob006.
That’s my problem.
How do I pass $company in order to make it work?
I’ve tried setting a public property. I’ve tried to play with __construct method… nothing worked so far…

For those who may have the same problem:

I got it done like this:

class FatFaturas extends \yii\db\ActiveRecord
{
public static $company;

public function __construct($company)
{
        self::$company = $company;
}

// override of activerecord  getDB method
public static function getDb()
{
    return \common\skeyra\utils::get_client_connection(self::$company);
}

get_client_connection is just some code that returns a connection

model shall be instantiated like this: 

$something= new FatFaturas(5); e.g. for company number 5

1 Like