问题
In my database i have the following tables:
- courses (id, name, created_at, updated_at)
- students (id, name, created_at, updated_at)
- 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