假设我有这样的链接表:
lessons -> sections -> courses(课程表格是这个链条的顶端)
这些表通过一个键相互连接,这个键是一个id:
lessons.section_id = sections.id
sections.course_id = courses.id(课程表与课程表没有直接联系)
现在如何选择相关课程表行,例如在lessons控制器的更新方法中?是这样的吗?
$lesson = Lesson::find( $id );
$course = DB::table( 'lessons' )
->join( 'sections', 'lessons.section_id', '=', 'sections.id' )
->where( 'sections.id', $lesson->section_id )
->join( 'courses', 'sections.course_id', '=', 'courses.id' )
->first();或者还有更好的方法吗?
发布于 2018-07-26 04:36:40
像这样使用关系
课程模型
public function getCourseAttribute()
{
return $this->section->course;
}
public function section()
{
return $this->belongsTo(Section::class);
}截面模型
public function course()
{
return $this->belongsTo(Course::class);
}你的控制器是这样的:
$lesson = Lesson::find( $id );
$course = $lesson->course;https://stackoverflow.com/questions/51526951
复制相似问题