doulang6695 2017-08-14 13:29 采纳率: 100%
浏览 9
已采纳

Laravel 5.4关系

I have 3 models and a pivot table:

SchoolYear - model

id

Course - model

id

schoolyear_id

course_student - pivot table

course_id

student_id

Student - model

id

Relationships are:

a SchoolYear hasMany Course

a Course belongsToMany Student trough course_student

a Student belongsToMany Course trough course_student

What is the fastest, more elegant way to find the students rolled in to a schoolyear and also to be able to sort it by Student properties?

        $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);
  • 写回答

1条回答 默认 最新

  • drcrc28428 2017-08-14 14:51
    关注

    Eloquent provides a set of methods to query relationship existence. has() if there are not conditions, or whereHas() if there is a condition.

    So, in your case, you want the students that have a related school year.

    $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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来