我想基于STUDENT TABLE
从CLASS TABLE
获取记录。
喜欢,RESULT = ['CLASS1'=>['STUDENT1','STUDENT3','STUDENT3'],'CLASS2'=>['STUDENT1','STUDENT3','STUDENT3']]
我正在做的是,基于ID获取所有类并在for循环中,在STUDENT table
中查找记录。并存储到数组中。
$class = ClassList::where(CLASS_LIST.'.class_id',$student->school_id)->where(CLASS_LIST.'.status','Active')->where(function($query)use($request){
if($request->has('class_id') && !empty($request->class_id)){
$query->where(CLASS_LIST.'.id',$request->class_id);
}
})->leftjoin(student_TABLE,student_TABLE.'.user_id',CLASS_LIST.'.created_by_user')->select(CLASS_LIST.'.id',CLASS_LIST.'.name',CLASS_LIST.'.status',CLASS_LIST.'.updated_at as class_members',student_TABLE.'.first_name',student_TABLE.'.last_name',CLASS_LIST.'.created_at')->get();
foreach($classs as $key=>$class){
$class_member = classs::where('class_id',$class->id)->where(class_TABLE.'.status','Active')
->join(student_TABLE,student_TABLE.'.student_id',class_TABLE.'.student_id')
->get();
$class->class_members = $class_member;
}
答案:所有类:
array:4 [
0 => array:7 [
"id" => 4
"name" => "CLASS 1"
"students"=> array:5 [
"first_name" => "kaushik"
"last_name" => "thakkar"
"user_id" => 9
"class_name" => "CLASS 1"
]
]
1 => array:7 [
"id" => 5
"name" => "CLASS 2"
"students"=> array:5 [
"first_name" => "kaushik"
"last_name" => "thakkar"
"user_id" => 9
"class_name" => "CLASS 1"
]
]
]
最佳答案
您可以像这样通过两个foreach
解决此问题
$classes = ClassList::all();
$students = Student::all();
$arr = array();
foreach ($classes as $key => $val) {
$id = $val->id;
$arr[$id]['data'] = $val;
}
foreach ($students as $key => $val) {
$parent = $val['class_id'];
if (isset($arr[$parent])) {
$arr[$parent]['children'][] = $val;
}
}
return $arr;
这使得结果类似于
Parents -> Childes
。阅读this question它可以帮助您理解。