【问题标题】:Invoking Eloquent method through Reflaction Class, Method not found error通过反射类调用 Eloquent 方法,找不到方法错误
【发布时间】:2019-12-21 07:15:16
【问题描述】:

我正在通过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 not found。那里有容易出错的代码。

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

我正在尝试使用 Reflation 获取具有 product 关系计数的模态。

检查此表,其中details 列包含类名、关系等。我正在使用折射和行中给出的详细信息重新创建它。

【问题讨论】:

  • 因为 withCount 不是 Model 方法,它在 Eloquent\Builder 上……你为什么要这样做?
  • 我有一个类名string 存储在数据库中,我必须提出它并计算它具有的关系模式的数量,这就是我使用反射的原因。是否有类似的解决方法来整理问题陈述?
  • 为什么类名在数据库中?试图通过将类名放入数据库来找出您正在解决的问题
  • 我有一个数据类型表,包含关于类、输入字段、类型、关系等的定义。请检查我附加到问题的图像。
  • 我提供了该示例 $class::where(...)->first(); .. 即使这些“静态”方法调用也在后台创建模型的新实例,with 不是静态方法,它是常规方法方法 ...__callStatic 正在发挥作用

标签: php laravel exception reflection eloquent


【解决方案1】:

你有你想使用的类名并且知道它是一个模型。您可以自己获取该类的新实例,或者只需将类名作为字符串即可对该类进行静态调用:

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

祝你的项目好运,看起来很有趣。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-25
    • 1970-01-01
    相关资源
    最近更新 更多