在Laravel中按数据透视表created_at排序 [英] Order by pivot table created_at in Laravel

查看:71
本文介绍了在Laravel中按数据透视表created_at排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的数据库中,我有以下表格:

In my database i have the following tables:

  1. 课程(ID,名称,created_at,updated_at)
  2. 学生(ID,姓名,created_at,updated_at)
  3. course_student (id,course_id,student_id,created_at,updated_at)
  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)

我正在尝试通过数据透视表course_student中的created_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:

学生模型:

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

课程模式:

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?

推荐答案

从学生那里获得课程:

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

这篇关于在Laravel中按数据透视表created_at排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆