Question

http://docs.phalconphp.com/en/0.6.0/reference/odm.html

Setting multiple databases¶

In Phalcon, all models can belong to the same database connection or have an individual one. Actually, when Phalcon\Mvc\Collection needs to connect to the database it requests the “mongo” service in the application’s services container. You can overwrite this service setting it in the initialize method:

<?php

//This service returns a mongo database at 192.168.1.100
$di->set('mongo1', function() {
 $mongo = new Mongo("mongodb://scott:nekhen@192.168.1.100");
 return $mongo->selectDb("management");
});

//This service returns a mongo database at localhost
$di->set('mongo2', function() {
$mongo = new Mongo("mongodb://localhost");
return $mongo->selectDb("invoicing");
});

Then, in the Initialize method, we define the connection service for the model:

<?php

class Robots extends \Phalcon\Mvc\Collection
{

    public function initialize()
    {
        $this->setConnectionService('management'); // here? 
    }

}
Was it helpful?

Solution

You are correct. The documentation was wrong. The correct usage is to set the appropriate service name (not the collection) using the setConnectionService.

http://docs.phalconphp.com/en/latest/reference/odm.html

<?php

// This service returns a mongo database at 192.168.1.100
$di->set(
    'mongo1', 
    function() 
    {
        $mongo = new Mongo("mongodb://scott:nekhen@192.168.1.100");
        return $mongo->selectDb("management");
    }
);

// This service returns a mongo database at localhost
$di->set(
    'mongo2', 
    function() 
    {
        $mongo = new Mongo("mongodb://localhost");
        return $mongo->selectDb("invoicing");
    }
);

Then, in the Initialize method, we define the connection service for the model:

.. code-block:: php

<?php

class Robots extends \Phalcon\Mvc\Collection
{
    public function initialize()
    {
        $this->setConnectionService('mongo1');
    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top