今天要先來討論Eloquent最直覺易懂的關係One To One/ One To Many/ Many To Many。
一對一的關係時(One To One):
Model | 擁有 | Model | 屬於 |
---|
User|hasOne|Profile|belongsTo
class User extends Model
{
public function profile()
{
return $this->hasOne('App\Profile');
}
...
}
class Profile extends Model
{
protected $fillable=['user_id','avatar'];
public function user()
{
return $this->belongsTo('App\User');
}
...
}
$this->belongsTo($model,$foreign_key,$owner_key);
$this->hasOne($model,$foreign_key,$localkey);
參數 | 預設 |
---|
foreign_key| ($model_name)_id =>user_id
owner_key/local_key|id
一對多的關係時(One To Many):
Model | 擁有 | Model | 屬於 |
---|
User|hasMany|Project|belongsTo
class User extends Model
{
public function profile()
{
return $this->hasMany('App\Project');
}
...
}
class Project extends Model
{
public function owner()
{
return $this->belongsTo('App\User', 'owner_id');
}
}
多對多的關係時(Many To Many):
之前說過多對多的關係會需要三個資料表,以多個使用者可以被邀請加入多個計畫中為例,會需要users/projects/project_user(預設值)三個資料表。
Model | 屬於 | Model | 屬於 |
---|
User|belongsToMany|Project|belongsToMany
class User extends Model
{
public function invitedProject()
{
return $this->belongsToMany('App\Project', 'member_project', 'member_id', 'project_id');
}
...
}
class Project extends Model
{
public function members()
{
return $this->belongsToMany('App\User','member_project','project_id','member_id');
}
}
參數 | 預設 |
---|
$intermediate_table_name|($model_name1)_($model_name2)=>’project_user’(照字母順序)
$(self_model_name)_id |在User(Model)中規定時,($model_name1)_id =>user_id
$(other_model_name)_id|另一個外鍵Project(Model),($model_name2)_id =>project_id
PS:
我一開始有點搞不清楚$user->projects()和$user->projects差別,常常會弄錯要不要加(),基本上透過Laravel提供的 php artisan tinker 和之前提過的dd(),則可以看出兩者間的差別:
指令 | 傳回的型態 | 篩選的方法 |
---|
$user->projects| Illuminate\Database\Eloquent\Collection|用Collection所提供的方法
$user->projects()|Illuminate\Database\Eloquent\Relations\HasMany|使用Query Builder所提供的方法