一、什麼是 Eloquent 關聯?

在 Laravel 中,Eloquent ORM 提供了簡潔的方式來定義資料表之間的關聯,讓你可以:

  • 自動查詢關聯資料

  • 簡化 SQL JOIN

  • 使用直覺語法操作模型關聯

一對一(One to One)

範例情境

一個 User 有一個 Profile(個人檔案)

資料表結構

users profiles
 id  id
 name  user_id (外鍵)
   bio

 

Model 寫法

在 User model:

public function profile()
{
    return $this->hasOne(Profile::class);
}

在 Profile model:

public function user()
{
    return $this->belongsTo(User::class);
}

使用方式

$user = User::find(1);
$bio = $user->profile->bio;

$profile = Profile::find(1);
$name = $profile->user->name;

 

一對多(One to Many)

範例情境

一個 Agency 有很多 Girl

資料表結構 

agencies girls
 id  id
 name  name
  agency_id (外鍵)

 

Model 寫法

在 Agency model:

public function girls()
{
    return $this->hasMany(Girl::class);
}

在 Girl model:

public function agency()
{
    return $this->belongsTo(Agency::class);
}

使用方式

$agency = Agency::find(1);
$girls = $agency->girls;

$girl = Girl::find(2);
$agencyName = $girl->agency->name;

 

多對多(Many to Many)

範例情境

一個 Girl 可以屬於多個 Agency
一個 Agency 也可以有多個 Girl

資料表結構

agencies girls agency_girl_maps (pivot table)
 id  id  girl_id
 name  name  agency_id

 

Model 寫法

在 Girl model:

public function agencies()
{
    return $this->belongsToMany(Agency::class, 'agency_girl_maps', 'girl_id', 'agency_id');
}

 

在 Agency model: 

public function girls()
{
    return $this->belongsToMany(Girl::class, 'agency_girl_maps', 'agency_id', 'girl_id');
}

 

使用方式

$girl = Girl::find(1);
$girl->agencies; // 所屬 agency 列表

$agency = Agency::find(2);
$agency->girls; // 所屬 girl 列表

 

補充:with() 預載入關聯(避免 N+1)

$girls = Girl::with('agencies')->get(); // 預先載入 agency
$agencies = Agency::with('girls')->get(); // 預先載入 girls

 

Laravel 常見關聯方法一覽

方法 關聯型態 用於哪邊
hasOne()  一對一  父模型(如 User)
belongsTo()  一對一 / 多  子模型(如 Profile)
hasMany()  一對多  父模型(如 Agency)
belongsToMany()  多對多  雙方模型都要設定
with()  預載入關聯資料  查詢時
withPivot()  多對多時讀取中介表欄位  belongsToMany 中使用