php - 如何在 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();
});
});
我究竟做错了什么?
解决方案
如果你想保持这种结构,你的问题的解决方案是让方法返回闭包,如下所示:
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());
推荐阅读
- oracle - 从 Apache2.4 迁移到 OHS(Oracle HTTPS 服务器)后,我收到致命错误:未捕获错误:调用未定义函数 oci_connect()
- android - 内部测试人员从哪里下载 Google Play Android 应用程序?
- html - css:如何将一小组单词保持在一起而不会换行且不会溢出
- ethereum - Solidity 和 Web3 sha3() 方法返回别的东西
- java - 步骤定义 Java - Selenium WebDriver 从搜索结果中查找元素
- qt - QCryptographicHash::Sha3_256 在 Qt5.4 和 Qt5.8 中有所不同
- angularjs - 使用 JWT 对来宾/匿名用户进行身份验证
- ios - 寻呼机选项卡隐藏在 ios swift 中 XLPagerTabStrip 的导航栏下。(使用 XLPagerTabStrip)
- neo4j - 在 Neo4j 中使用开始/结束日期过滤关系
- css - Laravel Mix 将 CSS 导入 JS 文件导致 npm watch 出现无限循环