
# Các Mối Quan Hệ Trong Eloquent
Eloquent cung cấp một hệ thống mạnh mẽ để quản lý các mối quan hệ giữa các mô hình trong cơ sở dữ liệu. Các mối quan hệ giúp bạn dễ dàng lấy dữ liệu liên quan từ các bảng khác nhau. Dưới đây là các loại mối quan hệ phổ biến trong Eloquent và cách sử dụng chúng:
1. Mối Quan Hệ Một-Một (One-to-One)
Một mối quan hệ một-một liên kết hai mô hình với nhau, với mỗi bản ghi trong bảng đầu tiên liên kết với một bản ghi trong bảng thứ hai.
Ví Dụ:
// Mô hình User
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function profile()
{
return $this->hasOne(Profile::class);
}
}
// Mô hình Profile
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
Cấu Trúc Bảng:
users
table:id
,name
profiles
table:id
,user_id
,bio
2. Mối Quan Hệ Một-Nhiều (One-to-Many)
Một mối quan hệ một-nhiều cho phép một bản ghi trong bảng đầu tiên liên kết với nhiều bản ghi trong bảng thứ hai.
Ví Dụ:
// Mô hình Post
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function comments()
{
return $this->hasMany(Comment::class);
}
}
// Mô hình Comment
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public function post()
{
return $this->belongsTo(Post::class);
}
}
Cấu Trúc Bảng:
posts
table:id
,title
comments
table:id
,post_id
,content
3. Mối Quan Hệ Nhiều-Nhiều (Many-to-Many)
Mối quan hệ nhiều-nhiều cho phép nhiều bản ghi trong bảng đầu tiên liên kết với nhiều bản ghi trong bảng thứ hai thông qua bảng trung gian.
Ví Dụ:
// Mô hình Student
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
public function courses()
{
return $this->belongsToMany(Course::class);
}
}
// Mô hình Course
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Course extends Model
{
public function students()
{
return $this->belongsToMany(Student::class);
}
}
Cấu Trúc Bảng:
students
table:id
,name
courses
table:id
,title
course_student
table:student_id
,course_id
4. Mối Quan Hệ Một-Một (Polymorphic)
Mối quan hệ polymorphic cho phép một mô hình liên kết với nhiều mô hình khác theo cách linh hoạt.
Ví Dụ:
// Mô hình Comment
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public function commentable()
{
return $this->morphTo();
}
}
// Mô hình Post
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
}
// Mô hình Video
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Video extends Model
{
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
}
Cấu Trúc Bảng:
comments
table:id
,commentable_id
,commentable_type
,content
posts
table:id
,title
videos
table:id
,title
5. Mối Quan Hệ Một-Nhiều (Polymorphic)
Mối quan hệ một-nhiều polymorphic cho phép một mô hình liên kết với nhiều mô hình khác mà không cần phải tạo ra nhiều cột khóa ngoại. Điều này rất hữu ích khi bạn muốn một mô hình có thể liên kết với nhiều loại mô hình khác mà không cần tạo nhiều bảng trung gian.
Ví Dụ Cụ Thể
Giả sử bạn có một hệ thống mà người dùng có thể bình luận trên các bài viết (Post
) và video (Video
). Bạn có thể sử dụng mối quan hệ polymorphic để xử lý các bình luận mà không cần tạo bảng trung gian riêng cho mỗi loại mô hình.
Bước 1: Tạo Các Mô Hình và Cấu Trúc Bảng
- Tạo Model
Comment
namespace App\Models; use Illuminate\Database\Eloquent\Model; class Comment extends Model { /** * Thiết lập mối quan hệ polymorphic. */ public function commentable() { return $this->morphTo(); } }
- Tạo Model
Post
namespace App\Models; use Illuminate\Database\Eloquent\Model; class Post extends Model { /** * Thiết lập mối quan hệ một-nhiều polymorphic. */ public function comments() { return $this->morphMany(Comment::class, 'commentable'); } }
- Tạo Model
Video
namespace App\Models; use Illuminate\Database\Eloquent\Model; class Video extends Model { /** * Thiết lập mối quan hệ một-nhiều polymorphic. */ public function comments() { return $this->morphMany(Comment::class, 'commentable'); } }
- Tạo Cấu Trúc Bảng
-
Bảng
comments
Schema::create('comments', function (Blueprint $table) { $table->id(); $table->text('content'); $table->unsignedBigInteger('commentable_id'); $table->string('commentable_type'); $table->timestamps(); });
commentable_id
: ID của mô hình mà bình luận thuộc về.commentable_type
: Loại mô hình mà bình luận thuộc về (ví dụ:Post
hoặcVideo
).
- Bảng
posts
Schema::create('posts', function (Blueprint $table) { $table->id(); $table->string('title'); $table->timestamps(); });
- Bảng
videos
Schema::create('videos', function (Blueprint $table) { $table->id(); $table->string('title'); $table->timestamps(); });
-
Bước 2: Sử Dụng Mối Quan Hệ
1. Thêm Bình Luận
use App\Models\Post;
use App\Models\Video;
use App\Models\Comment;
// Thêm bình luận cho một bài viết
$post = Post::find(1);
$post->comments()->create([
'content' => 'Great post!',
]);
// Thêm bình luận cho một video
$video = Video::find(1);
$video->comments()->create([
'content' => 'Amazing video!',
]);
2. Truy Xuất Bình Luận
// Truy xuất bình luận của một bài viết
$post = Post::find(1);
foreach ($post->comments as $comment) {
echo $comment->content;
}
// Truy xuất bình luận của một video
$video = Video::find(1);
foreach ($video->comments as $comment) {
echo $comment->content;
}
3. Lấy Mô Hình Từ Bình Luận
// Lấy mô hình mà bình luận thuộc về
$comment = Comment::find(1);
echo $comment->commentable_type; // Ví dụ: App\Models\Post hoặc App\Models\Video
6.Mối Quan Hệ Nhiều-Nhiều (Polymorphic)
Mối quan hệ nhiều-nhiều polymorphic cho phép một mô hình liên kết với nhiều mô hình khác và ngược lại thông qua một bảng trung gian duy nhất. Điều này cho phép mô hình liên kết với nhiều mô hình khác mà không cần phải tạo nhiều bảng trung gian riêng biệt.
Ví Dụ: Tagging trên Bài Viết và Video
Cấu Trúc và Mô Hình
-
Tạo Mô Hình
Tag
namespace App\Models; use Illuminate\Database\Eloquent\Model; class Tag extends Model { /** * Thiết lập mối quan hệ nhiều-nhiều polymorphic. */ public function taggable() { return $this->morphTo(); } }
- Tạo Mô Hình
Post
namespace App\Models; use Illuminate\Database\Eloquent\Model; class Post extends Model { /** * Thiết lập mối quan hệ nhiều-nhiều polymorphic. */ public function tags() { return $this->morphToMany(Tag::class, 'taggable'); } }
- Tạo Mô Hình
Video
namespace App\Models; use Illuminate\Database\Eloquent\Model; class Video extends Model { /** * Thiết lập mối quan hệ nhiều-nhiều polymorphic. */ public function tags() { return $this->morphToMany(Tag::class, 'taggable'); } }
- Tạo Cấu Trúc Bảng
Schema::create('tags', function (Blueprint $table) { $table->id(); $table->string('name'); $table->timestamps(); }); Schema::create('taggables', function (Blueprint $table) { $table->unsignedBigInteger('tag_id'); $table->unsignedBigInteger('taggable_id'); $table->string('taggable_type'); $table->timestamps(); });
- Sử dụng
// Thêm tag cho một bài viết $post = Post::find(1); $tag = Tag::find(1); $post->tags()->attach($tag); // Thêm tag cho một video $video = Video::find(1); $tag = Tag::find(2); $video->tags()->attach($tag);
Kết Luận
- Một-Một (One-to-One): Liên kết mỗi bản ghi trong bảng đầu tiên với một bản ghi trong bảng thứ hai.
- Một-Nhiều (One-to-Many): Liên kết một bản ghi trong bảng đầu tiên với nhiều bản ghi trong bảng thứ hai.
- Nhiều-Nhiều (Many-to-Many): Liên kết nhiều bản ghi trong bảng đầu tiên với nhiều bản ghi trong bảng thứ hai thông qua bảng trung gian.
- Polymorphic: Cho phép liên kết linh hoạt với nhiều mô hình khác.
Các mối quan hệ trong Eloquent giúp bạn dễ dàng quản lý và truy xuất dữ liệu liên quan trong ứng dụng của bạn, làm cho việc tương tác với cơ sở dữ liệu trở nên dễ dàng và trực quan hơn.
Danh mục
Bài viết liên quan

Quản Lý Thời Gian Tự Động Trong Eloquent
Author: | ADMIN |
---|

Basic Eloquent Model and MVC
Author: | ADMIN |
---|

Eager Loading
Author: | ADMIN |
---|

Database: Seeding
Author: | ADMIN |
---|
Bài viết khác

Blade Basics
Author: | ADMIN |
---|

9 Mẹo Hữu Ích Khi Sử Dụng Blade Trong Laravel
Author: | ADMIN |
---|

Hiển thị giá trị trong Blade
Author: | ADMIN |
---|