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

时间:2018-07-29 12:20:41

标签: laravel laravel-5.3 laravel-5.4 laravel-5.5 laravel-5.6

我试图根据路由类型在控制器中动态加载模型。但是,当我运行程序时,我收到一条消息,提示“找不到类”。这是我的代码以及我用来修复问题的stackoverflow链接。

代码:

    $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);

链接:

Load in models dynamically in Laravel 5.1

这是一个很好的链接,但不适用于我,为什么简单的$ model :: all()无法正常工作。

2 个答案:

答案 0 :(得分:1)

您需要使用双反斜杠:

import React, {Component} from 'react';
import fire from '../../config/Fire';
import classes from './Home.css';
import Aux from '../../hoc/Aux';
import Taco from '../../components/taco/Taco';

class Home extends Component {
constructor(props) {
    super(props);
    this.taco = this.taco.bind(this);
    this.state = {
        flag: false
    }
}

nextPage() {
    this.setState({flag: true});
}

render() {
    const flag = this.state.flag;

    if(flag) {
      return <Taco/>;
    }

    return (
        <Aux>
            <h1 className={classes.ChooseTruck}>Choose your favorite truck!</h1>
            <button
                type="button"
                className="btn btn-outline-primary btn-lg btn-block"
                onClick={this.nextPage}>Food Truck
            </button>
        </Aux>
    );
  }
}

export default Home;

尝试使用$class = "App\\Models\\$model"; 助手来解析模型:

app

答案 1 :(得分:0)

在班级名称中添加另一个斜杠:

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

而不是:

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