在 yii2 中通过 table 名称获取模型

Get model by table name in yii2

我在几个模型中有一个方法,以不同的方式实现。 我只知道数据库中 table 的名称。我必须找到这个 table 的模型。 怎么办?

interface BaseIndexedModel
{
    public function writeSometext();
}

并且一些模型实现了它。例子

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";
    }
}

接下来在某个事件上我需要调用所需的模型和此方法。但是调用的时候只会知道数据库table,不知道模型

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

得到table名字后可以这样操作

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;
}

你可以调用这个函数 并检查它是否存在

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

这个允许您在 table 名称中包含 1 个以上的单词。与 Ahmed Sunny 发布的解决方案相反,后者仅适用于 2 个单词。

public function getModelName($tableName) {
    $tableSplit = explode("_",$ruleTableName);
    $className = '';

    foreach ($tableSplit as $word){
        $className .= ucfirst($word);
    }

    return $className;
}