Many to many Polymorphic Relationship cũng hơi phức tạp để hiểu. Ví dụ: nếu bạn có bài post, video và tag, bạn cần kết nối với nhau theo yêu cầu là mọi bài đăng đều có nhiều tag và video cũng như vậy. Ngoài ra, mỗi tag sẽ được liên kết với nhiều bài post hoặc video. Nhưng chúng ta có thể dễ dàng làm điều đó chỉ bằng một bảng "taggables". 

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 Many to many Polymorphic Relationship.

Trong ví dụ này, tôi sẽ tạo các bảng "posts", "videos", "tags" và "taggables". mỗi bảng được liên kết với nhau. bây giờ chúng ta sẽ tạo Many to many Polymorphic 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. 

Polymorphic Many to Many Relationship sẽ sử dụng  "morphToMany()" và "morphedByMany()" cho mối quan hệ.

Tạo migrations

Bây giờ chúng ta sẽ tạo bảng "posts", "videos", "tags" và "taggables". Vì vậy, 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 tags

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

Migration bảng taggables

Schema::create('taggables', function (Blueprint $table) {
    $table->integer("tag_id");
    $table->integer("taggable_id");
    $table->string("taggable_type");
});

Tạo models

Tại đây, chúng ta sẽ tạo model bảng posts, videos và tags. chúng tôi cũng sẽ sử dụng "morphToMany()" và "morphedByMany()" cho các mối quan hệ.

Model bảng posts

<?php
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
 
class Post extends Model
{
    /**
     * Get all of the tags for the post.
     */
    public function tags()
    {
        return $this->morphToMany(Tag::class, 'taggable');
    }
}

Model bảng Videos

<?php
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
 
class Video extends Model
{
    /**
     * Get all of the tags for the post.
     */
    public function tags()
    {
        return $this->morphToMany(Tag::class, 'taggable');
    }
}

Model bảng tags

<?php
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
 
class Tag extends Model
{
    /**
     * Get all of the posts that are assigned this tag.
     */
    public function posts()
    {
        return $this->morphedByMany(Post::class, 'taggable');
    }
 
    /**
     * Get all of the videos that are assigned this tag.
     */
    public function videos()
    {
        return $this->morphedByMany(Video::class, 'taggable');
    }
}

Tuy vấn dữ liệu

$post = Post::find(1);	
dd($post->tags);

$video = Video::find(1);	
dd($video->tags);

$tag = Tag::find(1);	
dd($tag->posts);

$tag = Tag::find(1);	
dd($tag->videos);

Tạo mới dữ liệu

#
$post      = Post::find(1);
$tag       = new Tag;
$tag->name = "ManhDanBlog";
$post->tags()->save($tag);

#
$video     = Video::find(1);
$tag       = new Tag;
$tag->name = "Hi ManhDanBlog";
$video->tags()->save($tag);

#
$post       = Post::find(1);
$tag1       = new Tag;
$tag1->name = "Hi ManhDanBlog";
$tag2       = new Tag;
$tag2->name = "Hi ManhDanBlog";
$post->tags()->saveMany([$tag1, $tag2]);

#
$video      = Video::find(1);
$tag1       = new Tag;
$tag1->name = "Hi ManhDanBlog";
$tag2       = new Tag;
$tag2->name = "Hi ManhDanBlog";
$video->tags()->saveMany([$tag1, $tag2]);

#
$post = Post::find(1);
$tag1 = Tag::find(3);
$tag2 = Tag::find(4);
$post->tags()->attach([$tag1->id, $tag2->id]);

#
$video = Video::find(1);
$tag1  = Tag::find(3);
$tag2  = Tag::find(4);
$video->tags()->attach([$tag1->id, $tag2->id]);

#
$post = Post::find(1);
$tag1 = Tag::find(3);
$tag2 = Tag::find(4);
$post->tags()->sync([$tag1->id, $tag2->id]);

#
$video = Video::find(1);
$tag1  = Tag::find(3);
$tag2  = Tag::find(4);
$video->tags()->sync([$tag1->id, $tag2->id]);

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

Encrypted HTTP Live Streaming with Laravel FFMpeg

Encrypted HTTP Live Streaming with Laravel FFMpeg

HTTP Live Streaming (HLS)  HTTP Live Streaming (HLS) là một trong những giao thức phát trực tuyến video được sử dụng rộng rãi nhất . Mặc dù nó được gọi là HTTP "live" streaming, nhưng nó được sử dụn...

Laravel Mail Sending Redirector Listener

Laravel Mail Sending Redirector Listener

Trong quá trình phát triển web, việc gửi email là một chức năng quan trọng để thông báo, đặt lại mật khẩu, hoặc tương tác với người dùng. Tuy nhiên, khi chúng ta đang trong quá trình phát triển, vi...

Google Drive as Filesystem in Laravel

Google Drive as Filesystem in Laravel

Đối với một số dự án, bạn cần phải sử dụng Google Drive (với tài khoản @gmail.com cá nhân hoặc tài khoản G Suite) làm nhà cung cấp bộ nhớ trong các dự án Laravel. Trong bài đăng này, tôi sẽ hướng d...

Defer in Laravel: Push Tasks to the Background

Defer in Laravel: Push Tasks to the Background

Deferred Functions trong Laravel Các phiên bản Laravel trước version 11, chúng ta thường sử dụng Queued Jobs cho phép thực hiện sắp xếp các tác vụ xử lý background . Nhưng đôi khi có những tác v...

Pipeline Design Pattern in Laravel

Pipeline Design Pattern in Laravel

Pipeline Design Pattern là nơi mà các dữ liệu được chuyển qua một chuỗi các nhiệm vụ hoặc giai đoạn. Pipeline hoạt động giống như một chuỗi dây chuyền lắp ráp, nơi dữ liệu được xử lý và sau đó, sẽ...

Laravel 9 REST API With Sanctum Authentication

Laravel 9 REST API With Sanctum Authentication

Laravel Sanctum Laravel Sanctum cung cấp một hệ thống authentication đơn giản cho các SPA, ứng dụng Mobile và API đơn giản sử dụng token. Sanctum cho phép ứng dụng của bạn phát hành các mã token...

Laravel Queue Workers With Systemd

Laravel Queue Workers With Systemd

Systemd chủ yếu được sử dụng để quản lý các service trên môi trường Linux, nhưng nó cũng cho phép chúng ta quản lý các service với quyền không phải là root. Điều này, làm cho systemd trở thành một giả...

Laravel One to One Eloquent Relationship

Laravel One to One Eloquent Relationship

Mối quan hệ một-một là một mối quan hệ rất cơ bản. Trong hướng dẫn này, tôi sẽ hướng dẫn bạn cách tạo dữ liệu và truy xuất dữ liệu bằng Eloquent Model. Trong hướng dẫn này, tôi sẽ tạo hai bảng là u...

Export CSV from AWS RDS - Import into MySQL with Laravel

Export CSV from AWS RDS - Import into MySQL with Laravel

Transfer Database Trong quá trình phát triển và bảo trì dự án, nhiệm vụ di chuyển cơ sở dữ liệu từ hệ thống này sang hệ thống khác là một nhiệm vụ khá là phổ biến. Chúng ta thường sẽ sử dụng câu...

ManhDanBlogs