在資料庫設計中,不同資料表之間通常會有關聯關係,前幾天介紹的Eloquent ORM 幫我們簡化了這些關聯的操作,讓你不必自己手寫複雜的 SQL!接下來今天我們要認識 一對一(One-to-One) 和 一對多(One-to-Many)
資料表設計:
users
表:存放使用者基本資料profiles
表:多一個 user_id
外鍵// migration for profiles
Schema::create('profiles', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->string('phone');
$table->string('address');
$table->timestamps();
});
// User.php
public function profile()
{
return $this->hasOne(Profile::class);
}
// Profile.php
public function user()
{
return $this->belongsTo(User::class);
}
// 取得User的個人資料
$user = User::find(1);
$profile = $user->profile;
// 取得個人資料對應的使用者
$profile = Profile::find(1);
$user = $profile->user;
資料表設計:
posts
表comments
表:多一個 post_id
外鍵// migration for comments
Schema::create('comments', function (Blueprint $table) {
$table->id();
$table->foreignId('post_id')->constrained()->onDelete('cascade');
$table->text('content');
$table->timestamps();
});
// Post.php
public function comments()
{
return $this->hasMany(Comment::class);
}
// Comment.php
public function post()
{
return $this->belongsTo(Post::class);
}
// 取得文章的所有留言
$post = Post::find(1);
$comments = $post->comments;
// 取得留言對應的文章
$comment = Comment::find(1);
$post = $comment->post;
外鍵命名:Laravel 預設會找 表名稱_id
(例如 user_id
、post_id
)
外鍵約束:記得用 constrained()
建立關聯,資料一致性更好
hasOne
vs belongsTo
:
hasOne
→ 擁有關聯的一方(例如 User 有 Profile)belongsTo
→ 屬於某一方的資料(例如 Profile 屬於 User)