通过字符串调用 Laravel 模型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34409665/
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 12:51:21  来源:igfitidea点击:

Call Laravel model by string

phplaravellaravel-5.1

提问by Parampal Pooni

Is it possible to call a Laravel model by string?

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

This is what i'm trying to achieve but its failing:

这就是我想要实现的目标,但它失败了:

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

I get the following exception:

我收到以下异常:

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

回答by patricus

Yes, you can do this, but you need to use the fully qualified class name:

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

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

If your model name is stored in something other than a plain variable (e.g. a object attribute), you will need to use an intermediate variable in order to get this to work.

如果您的模型名称存储在普通变量(例如对象属性)以外的其他内容中,您将需要使用中间变量才能使其工作。

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

回答by Emeka Mbah

Try this:

尝试这个:

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

回答by Zia

Yes you can do it with more flexible way. Create a common function.

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

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();
}

Now you can call this method in different ways.

现在您可以通过不同的方式调用此方法。

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

By the way I like to use such functions.

顺便说一下,我喜欢使用这样的功能。

回答by Manojkiran.A

if you use it in many of the places use this function

如果您在许多地方使用它,请使用此功能

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

Example if you want to get all the user

例如,如果您想获取所有用户

Scenario 1:

场景一:

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

Scenario 2:

场景2:

if your model in in custom namespace may be App\Models

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

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

Hope it helps

希望能帮助到你

回答by itepifanio

This method should work well:

这种方法应该很有效:

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

My project has multiple subdirectory and this function work well. So I recover the namespace of the model with $model = current($this->getNamespace($this->request->get('model')));Then I just have to call my query: $model::all()

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

回答by Sheetal Mehra

You can also try like this:-

你也可以这样试试:-

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;
 }

}