Isnt this more or less the same as you did here?
Dec 3, 2019
17
Level 50
Laravel groupBy query (API Resource)
Hi
I am trying to get a student marks details that are group by exam_type. I need to create a API in below format. But I am unable to do that one. I need help with building query.
{
"success": true,
"data": [
{
"exam_type": "Annually",
"details":[
{
// all student marks details group by exam_type
"student_id": 89,
"subject": "English",
"marks": "50",
"marksgrade": "B",
"total": "300",
"grade": "B",
"percentage": "50",
"year": "2019"
},
{
// all student marks details group by exam_type
"student_id": 89,
"subject": "Mathematics",
"marks": "50",
"marksgrade": "B",
"total": "300",
"grade": "B",
"percentage": "50",
"year": "2019"
},
],
}
]
}
what I have tried
$marks = StudentMarksResource::collection(StudentsMark::whereIn('academic_id',$ids)
->whereIn('student_id',$studentid)->get()->groupBy('exam_type'));
Resource file
public function toArray($request)
{
return [
'exam_type' => $this->exam_type,
'class_id' => Course::find($this->class_id),
'batch_id' => Batch::find($this->batch_id),
'student_id' => Student::find($this->student_id),
'subject' => $this->subject,
'marks' => $this->marks,
'marksgrade' => $this->marksgrade,
'total' => $this->total,
'grade' => $this->grade,
'percentage' => $this->percentage,
'year' => $this->year,
];
}
how i am sending the data
return response()->json(['success' => true,'data' => $marks,'status' => 200]);
Level 50
@sinnbeck @bugsysha I have made changes like this
$exam_types = StudentsMark::whereIn('academic_id',$ids)->whereIn('student_id',$studentid)->distinct()->get(['exam_type','academic_id','student_id']);
$marks = StudentMarksResource::collection($exam_types);
resource file is
public function toArray($request)
{
return [
'exam_type' => $this->exam_type,
'details' => StudentMarks::where('academic_id', $this->academic_id)
->where('student_id', $this->student_id)
->where('exam_type',$this->exam_type)
->get(),
];
}
thank you once again
Please or to participate in this conversation.