首页 > 解决方案 > 如何在 laravel 中调用命名函数作为回调?

问题描述

我的模型中有两个功能:

function getPersonsByGroup($groupId, $callback) {
        $group = StutGroup::where('stg_id', $groupId)->get();
        $persons = [];
        foreach($group as $gr) {
            foreach($gr->students as $stud) {
                $persons[] = $stud->person;
            }
        }
        return $callback(collect($persons));
    }

function joinStudentsToPersons($person) {
    return $person->each(function ($pers) {
            $pers->student = \DB::connection('pgsql2')->table('students')->where('stud_pers_id', $pers->pers_id)->get();
        });
    }

我试图getPersonsByGroup在我的控制器中调用函数,将引用传递给回调,如下所示:

$students = $studGroup->getPersonsByGroup($request->group, $studGroup->joinStudentsToPersons);

但是,如果我将匿名函数传递给getPersonsByGroup一切正常:

$students = $studGroup->getPersonsByGroup($request->group, function($person) {
      return $person->each(function ($pers) {
          $pers->student = \DB::connection('pgsql2')->table('students')->where('stud_pers_id', $pers->pers_id)->get();
      });
});

我究竟做错了什么?

标签: phplaravel

解决方案


如果你想保持这种结构,你的问题的解决方案是让方法返回闭包,如下所示:

function joinStudentsToPersons() {
    return function ($person) {
        $person->each(function ($pers) {
            $pers->student = \DB::connection('pgsql2')->table('students')
                                ->where('stud_pers_id', $pers->pers_id)
                                ->get();
        });
    };
}

然后这样称呼它:

$students = $studGroup->getPersonsByGroup($request->group, $studGroup->joinStudentsToPersons());


推荐阅读