Laravel通过表名获取模型

Def*_*efy 5 php laravel

有没有办法按表名获取模型?

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

现在,我想要做的是按表名称获取模型,该名称等于"users".

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

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

编辑

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

Route::get('/{table}', 'ApiController@api');
Route::get('/{table}/filter', 'ApiController@filter');
Route::get('/{table}/sort', 'ApiController@sort');
Route::get('/{table}/search', 'ApiController@search');
Run Code Online (Sandbox Code Playgroud)

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

api/users/search?id=1
Run Code Online (Sandbox Code Playgroud)

然后在控制器上,例如:

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;
}
Run Code Online (Sandbox Code Playgroud)

小智 9

也许这样的事情可以帮助你:

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

if(class_exists($className)) {
    $model = new $className;
}
Run Code Online (Sandbox Code Playgroud)


Mar*_*sen 5

studly_case()str_singular()是已弃用的函数。

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

$className = 'App\\' . Str::studly(Str::singular($tableName));
Run Code Online (Sandbox Code Playgroud)