簡介

從前面內容中你已經了解資料庫中資料表間的關聯類型,那麼接下來就在 Laravel 中以 Eloquent Relationship 建立資料表關聯。

Laravel 處理資料表關聯的流程

  1. Migration 與資料表:在 Migration 檔案設定資料表間的關聯。
  2. 在 Model 撰寫關聯方法:依照關聯方式及從屬關係編寫交易邏輯。
  3. 測試關係函式

快速複習關聯類型

<aside> 💡 以下為了方便說明,Migration 與 Model 是分開建立的,你可透過 php artisan make:model Cgy -m 同時建立 Model Cgy(位於 /app/Models)與其 Migration 檔案(位於 /database/migrations),以及 php artisan make:model Task -m 同時建立 Model Task(位於 /app/Models)與其 Migration 檔案(位於 /database/migrations)。

</aside>

關聯類型:一對一

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/4dab77c3-6c5e-4076-998b-606894589b78/Untitled.png

Migration 與資料表

上圖是兩個資料表及其欄位的示意圖:記載工作內容的 tasks 資料表,以及記載工作分類的 cgies 資料表。圖中 tasks 資料中的 cgy_id 欄位有箭頭指向了 cgies 資料表的 id 欄位,tasks 資料表的 id 欄位與 cgies 資料的 id 欄位有 <pk>(主鍵,Primary Key) 標示,tasks 資料表的 cgy_id 欄位標示了<fk>(外鍵,Foreign Key)。

如果要建立的資料表會設定關聯,那麼在建立時需考慮先後次序:以本例的情況需先建立 cgies 資料表的 Migration,然後再建立 tasks 資料表的 Migration。

建立 Migration

建立 cgies 資料表的 Migration 指令:

php artisan make:migration create_cgies_table

cgys 資料表的 Migration 檔案內容: