【问题标题】:Laravel 5.4 relationshipsLaravel 5.4 关系
【发布时间】:2018-01-22 08:38:35
【问题描述】:

我有 3 个模型和一个数据透视表:

学年 - 模型

身份证

课程 - 模型

身份证

schoolyear_id

course_student - 数据透视表

课程编号

学生编号

学生 - 模特

身份证

关系是:

一个学年有很多课程

a Course belongsToMany Student 槽 course_student

a Student belongsToMany Course trough 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);

【问题讨论】:

  • 您希望以何种方式对学生属性进行排序?在例如一张桌子?
  • 你是什么意思?我想用 orderBy 订购它。只是想知道是否有更优雅的方式来获得结果?

标签: php mysql laravel laravel-5 relationship


【解决方案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);

【讨论】:

  • 这就是我正在寻找的 :) 谢谢@patricius!
猜你喜欢
  • 1970-01-01
  • 2017-10-25
  • 2017-09-22
  • 2017-10-01
  • 2017-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多