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.

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 tablees and the other tableen). 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();
}


6.5k
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.