是否可以通过字符串调用Laravel模型?
这是我想要实现的目标,但失败了:
$model_name = 'User';
$model_name::where('id', $id)->first();
我收到以下异常:
exception 'ErrorException' with message 'Undefined variable: User'
是的,您可以这样做,但是您需要使用完全限定的类名:
$model_name = 'App\Model\User';
$model_name::where('id', $id)->first();
如果您的模型名称存储在普通变量(例如,对象属性)之外的其他内容中,则需要使用中间变量才能使其正常工作。
$model = $this->model_name;
$model::where('id', $id)->first();
尝试一下:
$model_name = 'User';
$model = app("App\Model\{$model_name}");
$model->where('id', $id)->first();
是的,您可以通过更灵活的方式进行操作。创建一个通用函数。
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
通过我喜欢使用此类功能的方式。
如果您在许多地方使用它,请使用此功能
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();
希望有帮助
此方法应该很好用:
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()
您也可以这样尝试:-
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;
}
}