简体   繁体   English

仅使用 mysql 查询从第二个表中以第一个表作为数组获取记录

[英]Getting records from second table with first table as array using mysql query only

I want to fetch the record from STUDENT TABLE based on CLASS TABLE .我想根据CLASS TABLESTUDENT TABLE中获取记录。 Like,喜欢,

RESULT = ['CLASS1'=>['STUDENT1','STUDENT3','STUDENT3'],'CLASS2'=> ['STUDENT1','STUDENT3','STUDENT3']]

What I am doing is, fetching all classes and In for loop based on Id, looking for records in STUDENT table .我正在做的是,根据 Id 获取所有类和 In for 循环,在STUDENT table中查找记录。 and storing into array.并存储到数组中。

$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;
            }

ANSWER: ALL CLASSES:答案:所有课程:

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"
     ]
  ]
]

You can solve this by two foreach like this你可以像这样通过两个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;

That makes the results like Parents -> Childes .这使得结果类似于Parents -> Childes

read this question it can help you to understand.阅读这个问题它可以帮助你理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM