首页 > 解决方案 > 通过反射类调用 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 获取具有关系计数的模态。

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

标签: phplaravelexceptionreflectioneloquent

解决方案


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

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

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


推荐阅读