是否可以通过字符串调用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();
这个方法应该能很好地工作:
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()
如果您在许多地方使用它,请使用此函数
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();
希望它能帮助
是的,您可以用更灵活的方式来完成。创建一个通用函数。
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
顺便说一下,我喜欢使用这样的函数。
您也可以这样尝试:-
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;
}
}