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

Change model source dinamycally using query builder

My scenario here is that I have to tables with the exactly same structure but the table name (one of them table_es and the other table_en). So there is no need for two different models.

Is there a way that I could change the model source ( change the table name ) when executing a query with query builder?

$models = ['ModelA','ModelB'];
$builder = $this->modelsManager->createBuilder()
  ->where('id=?0', [$id])
  ->limit(20)
  ->orderBy('Robots.name');

$resultSetOutput = []; 
foreach($modellist as $m){
    $builder->from($m);
    resultSetOutput[$m] = $builder->getQuery()->execute();
}


11.2k
Accepted
answer

Thanks @jeffreycahyono, this is a way to solve my problem.

The problem I have is that I have just one model and two tables, both of them belonging to the same model. I'd like to be able to change the model source (table) and the query builder dinamically. For exemple:


public static function getPosts($language) 
{
     $builder =  \Phalcon\Di::getDefault()->get('modelsManager')->createBuilder();
     $bulder->setModelSource('table_' . $language)
     ...
}

Sorry, I might have not explained clearly.