php - 通过反射类调用 Eloquent 方法,找不到方法错误
问题描述
我通过ReflactionClass
如下代码调用模态方法,
public static function get($class = 'App/Tag'){
$modal = new ReflectionClass($class);
if($modal->hasMethod('all')){
$data = $modal->getMethod('all')->invoke($modal);
return (json_encode($data));
}else{
throw new MethodNotFoundException();
}
}
上面给出的函数工作正常,并使用 eloquent 的all()
方法获取所有数据。但是当我尝试获取模式和关系时,我遇到了withCount
找不到的方法。那里有容易出错的代码。
public static function get($class = 'App/Tag' , $cnt = true){
$modal = new ReflectionClass($class);
if($modal->hasMethod('get') && ($cnt ? $modal->hasMethod('withCount') : true)){
$data = $modal->getMethod('withCount')->invokeArgs($modal, ['product'])->getMethod('get')->invoke($modal);
return (json_encode($data));
}else{
throw new MethodNotFoundException();
}
}
我正在尝试product
使用 Reflation 获取具有关系计数的模态。
解决方案
你有你想使用的类名并且知道它是一个模型。您可以自己获取该类的新实例,或者只需将类名作为字符串进行静态调用:
$model = new $class;
$model = app($class); // using the application container to resolve the class
$res = $model->where(...)->withCount(...)->get();
// static call syntax
$res = $class::withCount(...)->where(...)->get();
祝你的项目好运,它看起来很有趣。
推荐阅读
- q-learning - Q-learning中的环境
- laravel - laravel 语法错误,期望 ',' ,期望 ';'
- typescript - 与较新版本相比,Typescript Exclude<> 在 3.8 和以前版本中的行为不同
- flutter - 如何在 VS Code 中打开模拟器或连接 LD Player 进行颤振?
- javascript - 需要使用 fetch 从(laravel api)获取数据,然后将其解析到另一个函数
- arrays - 针对异常数组检查对象字符串
- sql-server - ADODB 通过 Excel 连接到 SQL-Server
- assembly - 当您需要将参数传递给过程时, lea 对于获取变量的地址有什么用处?
- r - R 文件的文件路径影响设置断点的可能性
- javascript - d3.js 使用 selection.join 插入交替的兄弟姐妹