2017-08-14 220 views
0

我有3个模型和数据透视表:Laravel 5.4关系

学年 - 模型

ID

课程 - 模型

ID

schoolyear_id

course_student - 透视表

COURSE_ID

student_id数据

学生 - 模型

ID

关系是:

一学年的hasMany课程

课程belongsToMany学生槽course_student

一个学生belongsToMany课程槽course_student

什么是最快的,更优雅的方式找同学卷入一个学年,也可以通过学生属性进行排序?

 $year = SchoolYear::firstOrCreate(['anul'=>Carbon::now()->year]); 
     $courses = $year->courses; 
     $students = collect([]); 
     foreach($courses as $course){ 
      $course_students = $course->students; 
      foreach($course_students as $course_student){ 
       $students->push($course_student); 
      } 
     } 
     dd($year, $students); 
+0

您想以何种方式对学生属性进行排序?在例如一张桌子? –

+0

你的意思是?我想用orderBy来订购它。只是想知道是否有更优雅的方式来获得结果? – Zoli

回答

1

Eloquent提供了一组查询关系存在的方法。 has()如果没有条件,或者whereHas()如果有条件。

因此,就你而言,你希望有相关学年的学生。

$year = SchoolYear::firstOrCreate(['anul'=>Carbon::now()->year]); 

// assumes Student has a "courses" relationship, 
// and Course has a "schoolYear" relationship 
$students = Student::whereHas('courses.schoolYear', function ($query) use ($year) { 
     return $query->where('anul', $year->anul); 
    }) 
    ->get(); 

dd($year, $students); 
+0

这就是我正在寻找:) 谢谢@patricius! – Zoli