Is there way to use OO-power of QueryBuilder with defined DB-connection? [NOT SOLVED]

Hi!

My another question is about using OO-features of QueryBuilder with pre-defined DB-connection.

I know, that I can set "read connection" in the model depending on query parameters, but it is not the way I plan to produce queries to databases. My way is: 1. Choose DB-connection (choose right database-source) 2. Prepare query to choosen database with Query Builder 3. Execute PHQL-query

Is it real?

You can select in different moments the connection you want to use for executing the query using setConnectionService(), setReadConnectionService(), setWriteConnectionService(). If I understand correctly what you wanted to do, you can try like this:

public/index.php ```php //Set the database service $di->set('dbread', function() use ($config){ return new \Phalcon\Db\Adapter\Pdo\Mysql(array( "host" => $config->databaseread->host, "username" => $config->databaseread->username, "password" => $config->databaseread->password, "dbname" => $config->databaseread->dbname, "charset" => $config->databaseread->encoding )); });

$di->set('dbwrite', function() use ($config){ return new \Phalcon\Db\Adapter\Pdo\Mysql(array( "host" => $config->databasewrite->host, "username" => $config->databasewrite->username, "password" => $config->databasewrite->password, "dbname" => $config->databasewrite->dbname, "charset" => $config->databasewrite->encoding )); }); ```

And execute the query: ```php $content = new Content(); $content->setReadConnectionService('db_read'); $result = $content->query() ->where('type = :type:') ->bind(array('type' => 1)) ->order('id DESC') ->limit(20) ->execute(); ```

If you are doing raw queries, there are also other ways to select the connection you want: ```php public function getContents(){

  $sql = "SELECt * FROM content LIMIT 10";

  $content = new Content();
  $result = $content->getDI()->get('db_read')->query($sql);

  return new Resultset(null, $content, $result);

} ```



23.9k

Thank you, Vasco Pinheiro!

And execute the query:
$content = new Content();
$content->setReadConnectionService('db_read');
$result = $content->query()
      ->where('type = :type:')
      ->bind(array('type' => 1))
      ->order('id DESC')
      ->limit(20)
      ->execute();

This is almost that I need and I already tried to use this method, but: 1. I create my \Phalcon\Db object depending on number different parameters, so I just can not describe every DB-connection in \Phalcon\DI object. 2. I want to generate one query to the 2 or more models (tables) with QueryBuilder() (for ex: \Content and \SubContent()) with \Phalcon\Db created earlier "on-the-fly".

Now, for my purposes I use selectReadConnection(), but it is realy complicated to return same connection for every Model when I produce one query to the 2 or more tables. So, I want to tell to QueryBuilder: "Hey, that's the right connection. Please, use it for this query, ok?". Is it real?