簡體   English   中英

使用Eloquent從具有外鍵的單個表中獲取數據到另外兩個表-Laravel

[英]Using Eloquent to fetch data from a single table with foreign keys to two other tables - laravel

請給我三個模型:講師,水平,課程。

講師桌

| ID | Name_of_lecturer  
+----+----------------  
| 1 .| Prof John Doe  
+----+----------------  
| 2 .| Prof Jane Doe

等級表

| ID | Name 
+----+----------------  
| 1 .| Level 1  
+----+----------------  
| 2 .| Level 2

課程表

| ID | level_id | lecturer_id | course_info
+----+----------+-------------+----------------------------------  
| 1  | 2        | 3             a topic in level 2 by lecturer 3
+----+----------+-------------+----------------------------------
| 2  | 5        | 6           | a topic in level 5 by lecturer 6

我真的很困惑如何使用Eloquent從Levels Model中獲取每個課程的講師詳細信息。 任何幫助將不勝感激。 提前致謝。

由於一位講師可以開設許多課程,因此您正在尋找一對多的關系。 但是,由於您要從課程(許多)轉到講師(一個),因此您正在尋找以下內容:

在您的Course添加以下功能:

public function lecturer(){
    return $this->belongsTo(Lecturer::class);
}

這將允許您根據需要使用$course->lecturer()$course->lecturer->Name_of_lecturer

這是與Laravel文檔相關的鏈接: 雄辯的:關系-一對多(反向)

如果您不太熟悉laravel通過Models的口才,則可以將查詢與JOIN(內部聯接或任何您需要的)一起使用。 例如:

$lecturersDetails = DB::table('course')->join('lecturers','id','=','lecturer_id')->get();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM