我在控制器中的函数位于下方
public function getStudentsinGrade($grade, $school_id){
$students = Student::where('school_id', $school_id)->get();
$this -> grade = $grade;
$gradeStudent= $students->filter(function($value,$key){
return $value->grade == $this->grade;
});
if(count($gradeStudent) > 0){
return response()->json($gradeStudent);
}
else{
return response('No Registered Student');
}
}
我得到的回复在下面
*{
"2": <---this number here is the problem and it appeared when get API response
{
"id": 14,
"student_name": "Polly Grain",
"gender": "Female",
"stream_id": 1,
"school_id": 1,
"final_year_id": 2,
"grade": "Form Four"
},
"3": {
"id": 15,
"student_name": "Polly Grain",
"gender": "Male",
"stream_id": 3,
"school_id": 1,
"final_year_id": 2,
"grade": "Form Four"}
}*
我想要得到的回复是下面的
[{"id":1."student_name":"sae sddat";,"性别":"男性";,"stream_id":2."school_id":10,"final_year_id":12,"等级":"形式一";},{"id":1."student_name":"sae sddat";,"性别":"男性";,"stream_id":2."school_id":10,"final_year_id":12,"等级":"形式一";},{"id":1."student_name":"sae sddat";,"性别":"男性";,"stream_id":2."school_id":10,"final_year_id":12,"等级":"形式一";}]
要解决此问题,请首先将集合转换为数组,然后使用array_values()
函数来消除那些困扰您的恼人数组键。之后,转换回集合并将其作为json响应传递。IN代码:
public function getStudentsinGrade($grade, $school_id){
$students = Student::where('school_id', $school_id)->get();
$this -> grade = $grade;
$gradeStudent= $students->filter(function($value,$key){
return $value->grade == $this->grade;
});
if(count($gradeStudent) > 0){
$gradeStudent = collect(array_values($gradeStudent->toArray()));
return response()->json($gradeStudent);
}
else{
return response('No Registered Student');
}
}
现在,这将给你想要的结果如下:
{
"id": 14,
"student_name": "Polly Grain",
"gender": "Female",
"stream_id": 1,
"school_id": 1,
"final_year_id": 2,
"grade": "Form Four"
},
{
"id": 15,
"student_name": "Polly Grain",
"gender": "Male",
"stream_id": 3,
"school_id": 1,
"final_year_id": 2,
"grade": "Form Four"}
}
为什么不在查询中添加额外的where子句
public function getStudentsinGrade($grade, $school_id){
$students = Student::where('school_id', $school_id)
->where('grade', $grade)
->get();
if($students->count() > 0){
return response()->json($gradeStudent);
}
else{
return response('No Registered Student');
}
}