【问题标题】:Call Laravel model by string [duplicate]通过字符串调用 Laravel 模型 [重复]
【发布时间】:2015-12-22 06:23:20
【问题描述】:

是否可以通过字符串调用 Laravel 模型?

这是我想要达到的目标,但失败了:

$model_name = 'User';
$model_name::where('id', $id)->first();

我得到以下异常:

exception 'ErrorException' with message 'Undefined variable: User'

【问题讨论】:

  • 尝试使用完整的命名空间,例如$model_name = 'App\Http\Model\User';
  • 这行得通,但我实际上试图从实例变量中做到这一点,但仍然失败:${$this->model_name}::where
  • 你能描述一下你的评论吗?
  • 当然也可以app($model_name)->where(....)

标签: php laravel laravel-5.1


【解决方案1】:

是的,你可以这样做,但你需要使用完全限定的类名:

$model_name = 'App\Model\User';
$model_name::where('id', $id)->first();

如果您的模型名称存储在非普通变量(例如对象属性)中,则需要使用中间变量才能使其正常工作。

$model = $this->model_name;
$model::where('id', $id)->first();

【讨论】:

    【解决方案2】:

    试试这个:

    $model_name = 'User';
    $model = app("App\Model\{$model_name}");
    $model->where('id', $id)->first();
    

    【讨论】:

    • 你能解释一下你为什么使用 app() 吗?提前致谢
    • @RajaKhoury 获取实例,或者换句话说“return var_dump(app('App\User'));”看看结果
    【解决方案3】:

    这个方法应该很好用:

    private function getNamespace($model){
        $dirs = glob('../app/Models/*/*');
    
        return array_map(function ($dir) use ($model) {
            if (strpos($dir, $model)) {
                return ucfirst(str_replace(
                    '/',
                    '\\',
                    str_replace(['../', '.php'], '', $dir)
                ));
            }
        }, array_filter($dirs, function ($dir) use ($model) {
            return strpos($dir, $model);
        }));
    }
    

    我的项目有多个子目录,这个功能运行良好。所以我用$model = current($this->getNamespace($this->request->get('model')));恢复模型的命名空间 然后我只需要调用我的查询:$model::all()

    【讨论】:

      【解决方案4】:

      如果你在很多地方使用它,请使用这个功能

      function convertVariableToModelName($modelName='',$nameSpace='App')
              {
                  if (empty($nameSpace) || is_null($nameSpace) || $nameSpace === "") 
                  {                
                     $modelNameWithNameSpace = "App".'\\'.$modelName;
                      return app($modelNameWithNameSpace);    
                  }
      
                  if (is_array($nameSpace)) 
                  {
                      $nameSpace = implode('\\', $nameSpace);
                      $modelNameWithNameSpace = $nameSpace.'\\'.$modelName;
                      return app($modelNameWithNameSpace);    
                  }elseif (!is_array($nameSpace)) 
                  {
                      $modelNameWithNameSpace = $nameSpace.'\\'.$modelName;
                      return app($modelNameWithNameSpace);    
                  }
              }
      

      如果要获取所有用户的示例

      场景 1:

       $userModel= convertVariableToModelName('User');
        $result = $userModel::all();
      

      场景 2:

      如果您在自定义命名空间中的模型可能是App\Models

      $userModel= convertVariableToModelName('User',['App','Models']);
      $result = $userModel::all();
      

      希望对你有帮助

      【讨论】:

        【解决方案5】:

        是的,你可以用更灵活的方式来做到这一点。创建一个通用函数。

        function getWhere($yourModel, $select, $is_model_full_path=null, $condition_arr=null)
        {
            if(!$is_model_full_path){ // if your model exist in App directory
                $yourModel ="App\\$yourModel";
            }
            if(!$condition_arr){
                return $yourModel::all($select)->toArray();
            }
            return $App_models_yourModel::all($select)->where($condition_arr)->toArray();
        }
        

        现在你可以用不同的方式调用这个方法了。

        getWhere('User', ['id', 'name']); // with default path of model
        getWhere('App\Models\User', ['id', 'name'], true); // with custom path of model
        getWhere('User', ['id', 'name'], false, ['id', 1]); // with condition array
        

        顺便说一句,我喜欢使用这些功能。

        【讨论】:

          【解决方案6】:

          你也可以这样尝试:-

          use App\Model\User;
          
          class UsersController extends Controller
          {
          
           protected $model;
          
           public function __construct(User $model)
           {
              $this->model = $model;
           }
          
           public function getUser()
           {
            $data = $this->model->where('id', $id)->first();
          
            return $data;
           }
          
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-10-15
            • 1970-01-01
            • 2014-02-09
            • 2015-07-31
            • 1970-01-01
            相关资源
            最近更新 更多