如何根据来自第一个表LARAVEL的ID显示来自表关系的数据



我有三个表,课程表,章节表和教学大纲表。其中表课程与表章节的关系以及表章节与表教学大纲的关系。让我的表格下面看起来像:

#表课程:

public function up()
{
Schema::create('courses', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
$table->unsignedBigInteger('category_id')->default('1');
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade')->onUpdate('cascade');
$table->string('title');
$table->string('status')->default('publish');
$table->text('content')->nullable();
$table->timestamps();
});
}

表章节:

public function up()
{
Schema::create('sections', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('course_id');
$table->foreign('course_id')->references('id')->on('courses');
$table->string('name');
$table->timestamps();
});
}

最后一个表格教学大纲:

public function up()
{
Schema::create('syllabuses', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('section_id');
$table->foreign('section_id')->references('id')->on('sections')->onDelete('cascade')->onUpdate('cascade');
$table->string('title')->nullable();
$table->text('content')->nullable();
$table->text('description')->nullable();
$table->timestamps();
});
}

现在我只能根据Sections的ID显示表教学大纲中的数据,其中Sections根据Courses的ID显示,因为我不知道如何从与Sections ID相关的每一行中获取ID,并将其放入Syllabus::where('section_id',???)->get();中。任何能帮助我的人都非常感激。希望你理解我的意思。

在你可以看到的图片下面,我放了一些注释让你理解。绿框一中的问题。

在此处输入图像描述

首先定义模型中的关系。我想你的模型是:课程、章节和教学大纲

// Model Course
public function sections()
{
return $this->hasMany(Section::class);
}
// Model Section
public function course()
{
return $this->belongsTo(Course::class);
}
public function syllabuses()
{
return $this->hasMany(Syllabus::class);
}
// Model Syllabus
public function section()
{
return $this->belongsTo(Section::class);
}

现在,在您的控制器中,您可以通过获得指定的路线

// Controller Course
public function show($id)
{
$course = Course::with('sections', 'sections.syllabuses')->where('id', $id)->first();
}

在这个查询中,您有一个来自";课程";表,来自";章节";表和来自";教学大纲";桌子如果你正在使用laravel的刀片,那么你可以简单地通过以下方式访问它们:

// course
{!! $course->your_attribute !!}
// to access sections
@foreach($course->sections as $section)
@endforeach
// to access syllabuses
@foreach($course->sections as $section)
@foreach($section->syllabuses as $syllabus)
// Here you will have syllabuses for individual sections
@endforeach
@endforeach

https://laravel.com/docs/8.x/eloquent-relationships#one-到许多

在您有belongsTo关系的情况下,您需要研究laravel关系。

在您的教学大纲模型中添加。

public function section(){
return $this->belongsTo(Section::class, 'section_id');
}

然后你可以使用这将获得所有与那里相关的教学大纲部分。

Syllabus::with('section')->get();

最新更新