【问题标题】:Getting records from second table with first table as array using mysql query only仅使用 mysql 查询从第二个表中获取第一个表作为数组的记录
【发布时间】:2020-02-20 17:08:50
【问题描述】:

我想根据CLASS TABLESTUDENT TABLE 获取记录。 喜欢,

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

我正在做的是,根据 Id 获取所有类和 In 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"
     ]
  ]
]

【问题讨论】:

  • 请公布结果
  • 发布了结果。请帮帮我

标签: php mysql laravel multidimensional-array


【解决方案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可以帮助你理解。

【讨论】:

  • 您好,谢谢您的回答。有没有办法在没有 foreach 循环的情况下获得它?
  • 你可以使用连接,但这比连接简单,为什么你不使用foreach
  • 我不想一次次向数据库服务器发出请求,我认为会影响它的性能
猜你喜欢
  • 2019-12-05
  • 1970-01-01
  • 1970-01-01
  • 2014-03-28
  • 2019-11-15
  • 1970-01-01
  • 1970-01-01
  • 2021-11-26
  • 1970-01-01
相关资源
最近更新 更多