雄辩地查询多个表

时间:2018-06-19 14:46:29

标签: laravel eloquent

我正在使用Laravel 5.6。我正在尝试从grading_info表中查询信息,但我也想从student_info表中返回学生姓名和其他信息。我只想返回grading_info表中与当前登录的老师相关的记录。当前其返回的信息适用于所有教师。我知道我可以添加一个where子句,但是我试图学习口才好,并且想知道是否有任何方法可以做到这一点?

grading_info表中的师生可以有很多输入,并且任何老师都可以为任何学生评分。

我想返回这样的东西

{
    gradeID,
    gradeDate,
    gradeInfo
    .....
    student: {
        studentName,
        studentPhoneNumber,
        studentEmail
        ......
    }
}

用户表(仅存储教师,不存储学生)

  • id

teacher_info

  • teacherID(链接到用户表中的ID)

student_info

  • id(自动递增。与用户表无关)

grading_info

  • 学生ID(已链接到student_info的ID)
  • teacherID(链接到用户的ID)

用户模型

public function grades(){
    return $this->hasMany(GradingInfo::class, 'studentID');
}

GradingInfo模型

public function teacher(){
    return $this->belongsTo(User::class, 'id', 'teacherID');
}

public function student() {
    return $this->belongsTo(StudentInfo::class, 'studentID', 'id');
}

StudentInfo模型

public function grades() {
    return $this->hasMany(SessionInfo::class, 'studentID', 'id');
}

TeacherInfo模型

// Nothing in here. 

TeacherController

public function getGrades(Request $request)
{
    $user       = Auth::user(); // This is the teacher
    $grades     = $user->with('sessions.student')->orderBy('created_at', 'DESC')->get();
    return response()->json(['sessions' => $sessions], 200);
}

2 个答案:

答案 0 :(得分:1)

您在Many to Manyuser(teacher)之间拥有student(student_info) tables关系

  

用户模型

public function gradeStudents(){
    return $this->belongsToMany(StudentInfo::class, 'grading_info', 'teacherID', 'studentID');
}

public function info(){  //get teacher info 
   return $this->hasOne(TeacherInfo::class, 'teacherID');
}
  

StudentInfo模型

public function gradeTeachers(){
        return $this->belongsToMany(User::class, 'grading_info', 'studentID', 'teacherID');
}
  

现在获取数据(TeacherController)

public function getGrades(Request $request)
{
    $user     = Auth::user(); // This is the teacher
    $students = $user->gradeStudents; // it will return all graded students by logged in teacher 
    return response()->json(['students' => $students], 200);
}

此处grading_info是用于多对多关系的数据透视表

有关详细信息,请检查此https://laravel.com/docs/5.6/eloquent-relationships#many-to-many

从数据透视表中获取其他信息

如果您想在数据透视表(grading_info)中添加额外的信息,则在此表中添加列(info),然后需要像这样更改关系

public function gradeStudents(){
        return $this->belongsToMany(StudentInfo::class, 'grading_info', 'teacherID', 'studentID')
                    ->withPivot('info')
                    ->as('grade')
                    ->withTimestamps();              
}
  

现在,如果您获取数据

 $user = Auth::user(); // This is the teacher
 $students = $user->gradeStudents; 

 foreach($students as $student){
    print_r($student);
    print_r($student->grade->info);
    print_r($student->grade->created_at);
 }

答案 1 :(得分:0)

您应该使用hasOne,hasMany在模型中定义关系。 像这样的东西:

JSON.parse(myArray).name
相关问题