One to Many Polymorphic Model Relationship được sử dụng khi một model thuộc về nhiều model khác trên một model kết hợp duy nhất. Ví dụ: Nếu chúng ta có bảng post và video, cả hai đều cần thêm hệ thống nhận xét và bạn muốn có thể quản lý comment trong một bảng duy nhất cho cả post và video.

Vì vậy, trong hướng dẫn này, tôi sẽ hướng dẫn bạn tạo migrate, tạo dữ liệu và truy xuất dữ liệu trong One to Many Polymorphic Model Relationship.

Trong ví dụ này, tôi sẽ tạo bảng "posts", "videos" và "comments", mỗi bảng đều được liên kết với nhau. Bây giờ chúng ta sẽ tạo One to Many Polymorphic Model Relationship bằng cách sử dụng laravel Eloquent Model. Đầu tiên chúng ta sẽ tạo migrate, model, truy xuất dữ liệu và sau đó là cách tạo dữ liệu. Vì vậy, chúng ta sẽ thử một làm một ví dụ với cấu trúc bảng cơ sở dữ liệu như sau:

One to Many Polymorphic Relationship sẽ sử dụng "morphMany()" and "morphTo()" cho mối quan hệ.

Tạo migrations

Bây giờ chúng ta phải tạo migrate bảng posts, bảng videos và bảng comments. Bạn hãy tạo như hướng dẫn dưới đây:

Migration bảng posts

Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->string("name");
    $table->timestamps();
});

Migration bảng videos

Schema::create('videos', function (Blueprint $table) {
    $table->id();
    $table->string("name");
    $table->timestamps();
});

Migration bảng comments

Schema::create('comments', function (Blueprint $table) {
    $table->id();
    $table->string("body");
    $table->integer('commentable_id');
    $table->string("commentable_type");
    $table->timestamps();
});

Tạo models

Tại đây, chúng ta sẽ tạo model bảng post, video và comment. chúng ta cũng sẽ sử dụng "morphMany ()" và "morphTo ()" cho mối quan hệ của cả hai model.

Model bảng posts

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
 
class Post extends Model
{
    /**
     * Get all of the post's comments.
     */
    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable');
    }
}

Model bảng videos

<?php
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
 
class Video extends Model
{
    /**
     * Get all of the post's comments.
     */
    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable');
    }
}

Model bảng comments

<?php
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
 
class Comment extends Model
{
    /**
     * Get all of the owning commentable models.
     */
    public function commentable()
    {
        return $this->morphTo();
    }
}

Truy vấn dữ liệu

$post = Post::find(1);	
dd($post->comments);
$video = Video::find(1);	
dd($video->comments);

Tạo mới dữ liệu

$post = Post::find(1);	
$comment = new Comment;
$comment->body = "Hi ManhDanBlog";

$post->comments()->save($comment);
$video = Video::find(1);	
$comment = new Comment;
$comment->body = "Hi ManhDanBlog";
 
$video->comments()->save($comment);

Tôi hy vọng bạn thích hướng dẫn này. Nếu bạn có bất kỳ câu hỏi nào hãy liên hệ với chúng tôi qua trang contact. Cảm ơn bạn.

CÓ THỂ BẠN QUAN TÂM

Laravel Logging Of Database Queries

Laravel Logging Of Database Queries

Laravel là một Framework PHP mạnh mẽ và linh hoạt, giúp cho việc phát triển ứng dụng trở nên đơn giản và dễ dàng hơn. Một trong những tính năng hữu ích của Laravel là khả năng ghi nhật ký truy vấn...

Laravel Custom Rules

Laravel Custom Rules

Trong quá trình phát triển website Laravel, mình cảm thấy hệ thống Validation của Laravel rất tuyệt vời, nó cung cấp đã cung cấp cho chúng ta một bộ quy tắc kiểm tra dữ liệu, mà trong các trường hợp b...

Laravel Factories, Seeder

Laravel Factories, Seeder

Trong bài viết này, tôi sẽ hướng dẫn các bạn về cách tạo dữ liệu giả trong cơ sở dữ liệu bằng cách sử dụng Laravel Factory và Seed trong Database Seeder. Để tạo model factory, bạn cần chạy lệnh sau...

Eloquent Methods: whereDoesntHaveRelation and whereMorphDoesntHaveRelation

Eloquent Methods: whereDoesntHaveRelation and whereMorphDoesntHaveRelation

New Laravel 11.37: Eloquent Methods Laravel cung cấp cho chúng ta khả năng xây dựng các truy vấn dữ liệu mạnh mẽ với Eloquent ORM, giúp chúng ta có thể xử lý các truy vấn cơ sở dữ liệu phức tạp một...

Laravel UI Password Reset Expired

Laravel UI Password Reset Expired

Trong thư viện laravel/ui, thì chức năng password reset dù cho token có hết hạn thì vẫn có truy cập vào trang password reset, đến khi bạn submit form thì mới thông báo là token đã hết hạn. Nhưng có mộ...

ZSH-Artisan CLI and Docker: The Perfect Match for Laravel Development

ZSH-Artisan CLI and Docker: The Perfect Match for Laravel Development

Zsh Zsh viết tắt của “ Z Shell ” là một shell nâng cao cho hệ thống Unix và Linux. Nó được phát triển nhằm cung cấp các tính năng và khả năng cao hơn so với shell mặc định trên hầu hết các hệ thố...

Laravel Socialite Login With Gitlab

Laravel Socialite Login With Gitlab

GitLab GitLab là kho lưu trữ Git dựa trên web cung cấp các kho lưu trữ mở và riêng tư miễn phí, các khả năng theo dõi vấn đề và wiki. Đây là một nền tảng DevOps hoàn chỉnh cho phép các chuyên gia...

Laravel One to Many Eloquent Relationship

Laravel One to Many Eloquent Relationship

One to Many Relationship được sử dụng trong trường hợp một dữ liệu của một bảng được liên kết với một hoặc nhiều dữ liệu ở bảng khác. Ví dụ, một bài post có thể có nhiều comment. Vì vậy, trong hướn...

Laravel View

Laravel View

View là gì? Đây là phần giao diện (theme) dành cho người sử dụng. Nơi mà người dùng có thể lấy được thông tin dữ liệu của MVC thông qua các thao tác truy vấn như tìm kiếm hoặc sử dụng thông qua các...

ManhDanBlogs