如何使用关系获取数据

时间:2019-07-28 21:27:23

标签: php laravel

请使用ID(学期)建立链接

这是我的数据库:

  • Courses: id , title , pdf_file , extension , description , matieres_id and timetables
  • Matieres: id , matiere , semester_id and timetables
  • Semesters: id , semester, matieres_id and timetables

route / web.php

Route::get('/lms/semestre', 'HomeController@semestres');
Route::get('/lms/', 'HomeController@lms');
Route::get('/lms/matieres/{id}', 'HomeController@matieres');
Route::get('/lms/course/{id}', 'HomeController@course');
Route::get('/lms/courses', 'HomeController@courses');

Course.php(模型)

class Course extends Model
{
    use SoftDeletes;

    protected $table = 'courses';
    protected $fillable = ['id'];

    public function matiere()
    {
        return $this->belongsTo(\App\Matiere::class);
    }
}

Matiere.php(模型)

class Matiere extends Model
{
    protected $table = 'matieres';
    protected $fillable = ['id'];
    public function semestre()
    {
        return $this->belongsTo(\App\Semestre::class);
    }
}

Semestre.php(模型)

class Semestre extends Model
{
    protected $table = 'semestres';
    protected $fillable = ['id'];
    public function matiere()
    {
        return $this->belongsTo(\App\Matiere::class);
    }
}

我的问题是如何使用/lms/courses/{semester_id}来创建网址course->matiere_id->semesters并显示页面,其中是课程列表。 这对我来说非常复杂,我不想在课程表中创建列semester_id

1 个答案:

答案 0 :(得分:0)

尝试这个。 注意:确保在CourseDB之前先创建SemesterDB

数据库:

course_db:

Schema::create('courses', function (Blueprint $table) {
        ...
    });

semester_db:

Schema::create('semesters', function (Blueprint $table) {
...
$table->unsignedBigInteger('course_id');
...

$table->foreign('course_id')->references('id')->on('courses')->onDelete('cascade');
})

型号:

course_model:

protected $guarded = [];

public function semester() {
return $this->hasOne(Semester::class);
}

学期模式:

protected $guarded = [];

public function course() {
return $this->belongsTo(Course::class);
}

控制器:

App\Course;

public function index() {
$courses = Course::all();
dd($courses->semester);
}