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

I have two databases, How can I select a database?

Before this $builder, I want to select a database, what shall I do? I don't want to use raw SQL. Thanks!

$builder = $this->modelsManager->createBuilder()  
            ->columns($cols)  
            ->distinct(true)  
            ->from($ZUC)  
            ->leftJoin($ZU, "$ZU.user_id = $ZUC.user_id")  
            ->leftJoin($ZSC, "$ZUC.subclass_id = $ZSC.subclass_id")  
            ->leftJoin($ZC, "$ZC.class_id = $ZSC.class_id")  
            ->leftJoin($ZCH, "$ZCH.order_no = $ZUC.order_no")  
            ->where($conStr, $conArr)  
            ->orderBy($order);  


59.9k

Hello,

think you need raw SQL, something like that:

https://forum.phalcon.io/discussion/4332/how-to-create-database-with-phalcon

https://dev.mysql.com/doc/refman/8.0/en/create-database.html

Phalcon ORM is reading the database from the model files.

class MyModel extends \Phalcon\Mvc\Model
{
    public function getSource()
    {
        return 'your_db_name';
    };
}

You can write your logic here, determining which database should be used.



2.6k
edited Aug '18

it can return 'your_db_name', not 'table_name'? thanks in advance

Phalcon ORM is reading the database from the model files.

class MyModel extends \Phalcon\Mvc\Model
{
  public function getSource()
  {
      return 'your_db_name';
  };
}

You can write your logic here, determining which database should be used.



2.6k
Accepted
answer

share with you. Like this

  $zx_user_class = new ZxUserClass(); //your primary table
  $zx_user_class->setConnectionService('dbWrite'); // select databse
  $modelsManager = $zx_user_class->getModelsManager();
  $builder = $modelsManager->createBuilder()
   ->columns($cols)
   ->distinct(true)
   ->from($ZUC)
   ->leftJoin($ZU, "$ZU.user_id = $ZUC.user_id")
   ->leftJoin($ZSC, "$ZUC.subclass_id = $ZSC.subclass_id")
   ->leftJoin($ZC, "$ZC.class_id = $ZSC.class_id")
   ->leftJoin($ZCH, "$ZCH.order_no = $ZUC.order_no")
   ->where($conStr, $conArr)
   ->orderBy($order)


2.6k

Greetings and thank all of you very much!