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

different tables of the same model

Please tell me how can I change the model table from the controller? I need to get data from one table through one model, then from another table. How to change the table? was reviewed here but here is one table, and I need to get data from different tables of the same type with one model in the for loop. Is it possible? Thanks



8.4k
edited May '19

alter getSource() method in your model

and change the table name during runtime with Model::changeTable('other_table_name')

protected $table = 'default_table_name';

public function getSource()
{
    return static::$table;
}

public static function changeTable($table = 'default_table_name')
{
    static::$table = $table;
}

i didn't test test it before going into production

I don't believe it's possible. I think getSource() is only called once, when initializing the model. I think this because when I watch my query log - the queries to get table structure are only run once. Therefore any subsequent changes to it's output would have no effect.

I'd examine how to make 1 model per table. Maybe something like a generic wrapper:

class Super{
    private $ActiveModel;

    public setActiveModel($ActiveModel){
        $this->ActiveModel = $ActiveModel;
    }

    // forward on any undefined method calls to the active model
    public function __call($name,$arguments){
        return $this->ActiveModel->name(...$arguments);
    }

    // return any undefined variables from the active model
    public function __get($name){
        return $this->ActiveModel->$name;
    }
}

$MainObject = new Super();
$MainObject->setActiveModel(Table1Model::findFirst(['conditions here']));
$MainObject->someMethodCall();
$MainObject->setActiveModel(Table2Model::findFirst(['more conditions here']));
$MailObject->someOtherMethodCall();
$someVariable = $MailObject->someVariable;


8.4k

you are on point @Dylan Anderson my solution is for dynamic table name and can be changed once every run before first call.



14.4k

Thank you very much. You dispelled my doubts and helped determine the algorithm for constructing a database.