Laravel 按表名获取模型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37513473/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:53:57  来源:igfitidea点击:

Laravel get Model by Table Name

phplaravel

提问by Defy

Is there any way to get a model by table name?

有没有办法通过表名获取模型?

For example, I have a "User" model, its table is defined as protected $table = "users"

例如,我有一个“用户”模型,它的表定义为 protected $table = "users"

Now, what I want to do is to get the model by table name which is equal to "users".

现在,我想要做的是通过等于“users”的表名来获取模型。

This function is more like the reverse of Model::getTable();

这个功能更像是 Model::getTable();

I have searched everywhere but I could not find a solution, perhaps I might be missing something simple?

我到处搜索,但找不到解决方案,也许我可能遗漏了一些简单的东西?

EDIT

编辑

I am building something like an API :

我正在构建类似 API 的东西:

Route::get('/{table}', 'ApiController@api');
Route::get('/{table}/filter', 'ApiController@filter');
Route::get('/{table}/sort', 'ApiController@sort');
Route::get('/{table}/search', 'ApiController@search');

so in the address bar, for example when I search for the "users", I could just hit on the URL:

所以在地址栏中,例如当我搜索“用户”时,我可以直接点击 URL:

api/users/search?id=1

then on the controller, something like:

然后在控制器上,类似于:

public function search(){
  // get all the params

  // get the model function
  $model = //function to get model by table name

  // do some filtering, then return the model
  return $model;
}

回答by Igor R

Maybe something like this will help you:

也许这样的事情会帮助你:

$className = 'App\' . studly_case(str_singular($tableName));

if(class_exists($className)) {
    $model = new $className;
}

回答by huuuk

You must determine for which table name which class to call. I see 2 ways to do this.

您必须确定要为哪个表名调用哪个类。我看到有两种方法可以做到这一点。

Use Laravel's models naming convention as @IgorRynkovoy suggested

按照@IgorRynkovoy 的建议使用 Laravel 的模型命名约定

or

或者

Use some kind of dictionary

使用某种字典

public function search($tableName)
{
    $dictionary = [
        'table_name' => 'CLASS_NAME_WITH_NAMESPACE',
        'another_table_name' => 'CLASS_NAME_WITH_NAMESPACE',
    ];

    $className = $dictionary[$tableName];
    $models = null;

    if(class_exists($className)) {
        $models = $className::all();
    }

    // do some filtering, then return the model
    return $models;
}

回答by Mauro Baptista

I know that it is an old question, but it can help someone:

我知道这是一个老问题,但它可以帮助某人:

public function getModelFromTable($table)
{
    foreach( get_declared_classes() as $class ) {
        if( is_subclass_of( $class, 'Illuminate\Database\Eloquent\Model' ) ) {
            $model = new $class;
            if ($model->getTable() === $table)
                return $class;
        }
    }

    return false;
}

It will return the class name, so you need to instantiate it.

它将返回类名,因此您需要实例化它。

回答by Oleg

Alternative variant. I have my base model App\Models\Model This model have static method getModelByTable, ofcourse you can store this method anywhere you want.

替代变体。我有我的基本模型 App\Models\Model 这个模型有静态方法 getModelByTable,当然你可以把这个方法存储在你想要的任何地方。

public static function getModelByTable($table)
    {
        if (!$table) return false;
        $model = false;
        switch ($table) {
            case 'faq':
                $model = Faq::class;
                break;
            case 'faq_items':
                $model = FaqItems::class;
                break;
        }
        if ($model) {
            try {
                $model = app()->make($model);
            } catch (\Exception $e) {

            }
        }
        return $model;
    }

回答by Marcus Christiansen

studly_case()and str_singular()are deprecated functions.

studly_case()并且str_singular()是不推荐使用的函数。

You can use the Illuminate\Support\Strfacade.

您可以使用Illuminate\Support\Str门面。

$className = 'App\' . Str::studly(Str::singular($tableName));