Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Using a model on a different database

I have a site which uses products as its default database and has reference data stored in translations.

How do I make a model which use the table labels in translations as its default table?

I tried this:

    public function getSource()
    {
        return 'translations.labels';
    }

But I just get the following error message:

Table "translations.labels" doesn't exist on database when dumping meta-data for Project\V1\Models\Translations



31.3k
Accepted
answer

Hi,

if "translations" is your second database, and "products", the first one:

in config.php:

return new \Phalcon\Config(array(
    'one' => array(
        //'adapter'     => 'PostgreSQL',
        'host'        => 'localhost',
        'username'    => 'root',
        'password'    => 'myPGpass',
        'dbname'      => 'products',
    ),
    'two' => array(
        //'adapter'     => 'Mysql',
        'host'        => 'localhost',
        'username'    => 'root',
        'password'    => 'myMYpass',
        'dbname'      => 'translations',
    ),
));

in services.php:


use Phalcon\DI\FactoryDefault,
    Phalcon\Db\Adapter\Pdo\PostgreSQL as PgSqlAdapter,
    Phalcon\Db\Adapter\Pdo\Mysql as MySqlAdapter;

$di = new FactoryDefault();

$di->set('db', function() use ($config) {
    return new PgSqlAdapter(array(
        'host' => $config->one->host,
        'username' => $config->one->username,
        'password' => $config->one->password,
        'dbname' => $config->one->dbname
    ));
});
$di->set('translations', function() use ($config) {
    return new MySqlAdapter(array(
        'host' => $config->two->host,
        'username' => $config->two->username,
        'password' => $config->two->password,
        'dbname' => $config->two->dbname
    ));
});

in your labels Model:

    public function initialize()
    {
        $this->setConnectionService('translations');
    }
    public function getSource()
    {
        return 'labels';
    }

Thanks for that.