Laravel 5.6 中的动态模型加载问题

Issue in dynamic model loading in Laravel 5.6

我正在尝试根据路由类型在我的控制器中动态加载模型。但是当我 运行 编程时,我收到一条消息说 "class not found"。这是我的代码和 link 的 Whosebug,我用它来解决我的问题。

代码:

    $model = $this->getModelName($request->matchType);
    $class = "App\Models$model";
    if($model && class_exists($class))
    {
        $data = $class::where('type_id',$type)->firstOrFail();
    }
    else
    {
        $data = MyModel::find($type);
    }

    return $this->showOne($data);

Link:

这很好 link 但对我不起作用,为什么简单的 $model::all() 不起作用。

在您的 class 名称中再添加一个斜杠:

 $class = "\App\Models$model";

而不是:

 $class = "App\Models$model";

您需要使用双反斜杠:

$class = "App\Models\$model";

尝试使用 app 助手来解析模型:

$data = app($class)->where('type_id',$type)->firstOrFail();