Order by pivot table created_at in Laravel

扶醉桌前 提交于 2020-01-04 00:06:24

问题


In my database i have the following tables:

  1. courses (id, name, created_at, updated_at)
  2. students (id, name, created_at, updated_at)
  3. course_student (id, course_id, student_id, created_at, updated_at)

I'm trying to retrieve all the courses in which a student has enrolled order decrementally by the created_at value in the pivot table course_student

This is how i defined my models:

Student model:

   public function students () {
    return $this->belongsToMany(Student::class, 'course_student', 'course_id', 'student_id')->withTimestamps();
}

Course model:

public function courses () {
    return $this->belongsToMany(Course::class, 'course_student', 'student_id', 'course_id')->withTimestamps();
}

And this what i tried in my controller but it's not working.

public function enrolled() {
    $courses = Course::whereHas('students', function($query) {
        $query->where('user_id', auth()->id())
            ->orderBy('course_student.created_at','desc');
        })->get();

    return view('courses.enrolled', compact('courses'));
}

any idea how can i accomplish this?


回答1:


Get the courses from the student:

$student = Student::where('user_id', auth()->id())->first();
$courses = $student->courses()->orderByDesc('course_student.created_at')->get();


来源:https://stackoverflow.com/questions/53222860/order-by-pivot-table-created-at-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!