Search code examples
yii2yii2-model

Get model by table name in yii2


I have one method in several models, implemented in different ways. I only know the name of table in database. I must find model of this table. How to do?

interface BaseIndexedModel
{
    public function writeSometext();
}

and some models implement it. Example

class First extends \yii\db\ActiveRecord implements BaseIndexedModel
{
    public function writeSometext(){
       return "1";
    }
}

class Second extends \yii\db\ActiveRecord implements BaseIndexedModel
{
    public function writeSometext(){
       return "2";
    }
}

Next on a certain event I need to call the desired model and this method. But when I call, I will only know the database table, but not the model.

If table "first", First::writeSometext(); If table "second", Second:: writeSometext();


Solution

  • You can do it this way when you get the table name

    public function getModelName($table_name) {
        $table_name = 'first_table';  
        // $table_name = 'first';// if name is single word then comment the next line
        $table_split = explode("_",$table_name);
        $model = ucfirst($table_split[0]).ucfirst($table_split[1]);
        return $model;
    }
    

    you can call this function and check if it exists

    $model = getModelName($table_name);
    var_dump($model);