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

Export CSV from SQL Server - Import into MySQL with Laravel

Export CSV from SQL Server - Import into MySQL with Laravel

Transfer Database Trong quá trình phát triển và bảo trì dự án, việc 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á phổ biến. Giả sử bạn cần di chuyển dữ liệu từ SQ...

Easy Laravel Reverb Setup For Beginners

Easy Laravel Reverb Setup For Beginners

Laravel Reverb Lần đầu tiên, Laravel ra mắt một official package cho phép bạn xây dựng một Websocket Server. Trước đây, chúng ta phải sử dụng package bên thứ 3 như Laravel Websocket. Reverb được...

Amazon S3 Pre-Signed URL with DropzoneJs in Laravel

Amazon S3 Pre-Signed URL with DropzoneJs in Laravel

Chức năng upload file hay hình ảnh là một chức năng rất phổ biến, hầu hết các dự án đều có chức năng này. Đa số các nhà phát triển khi thực hiện chức năng upload file, thường sẽ sử dụng cách làm nh...

Laravel Routing

Laravel Routing

Route là gì? Đúng như tên gọi của nó, Route thực hiện chức năng định tuyến, dẫn đường cho các HTTP request gửi đến đúng nơi mà ta mong muốn. Với sự phát triển mạnh mẽ của ứng dụng web ngày nay, việc...

Fast Paginate in Laravel

Fast Paginate in Laravel

Laravel Fast Paginate là gì? Laravel Fast Paginate là một macro nhanh về phân trang offset/limit cho Laravel. Nó được sử dụng để thay thể paginate trong Laravel.Package này sử dụng phương pháp SQL t...

Integrating TinyMCE in Laravel 10 using Vite

Integrating TinyMCE in Laravel 10 using Vite

TinyMCE TinyMCE là một trình soạn thảo WYSIWYG được xây dựng trên nền tảng Javascript, được phát triển dưới dạng mã nguồn mở theo giấy phép MIT bởi Tiny Technologies Inc. TinyMCE cho phép ngư...

Laravel Socialite Login With Google

Laravel Socialite Login With Google

Google Google là một công cụ tìm kiếm trên internet. Nó sử dụng một thuật toán độc quyền được thiết kế để truy xuất và sắp xếp các kết quả tìm kiếm nhằm cung cấp các nguồn dữ liệu đáng tin cậy và ph...

Implementing Private User Folders with elFinder in Laravel

Implementing Private User Folders with elFinder in Laravel

elFinder elFinder là một trình quản lý tập tin mã nguồn mở dành cho web, được viết bằng JavaScript sử dụng jQuery UI. elFinder được phát triển dựa trên cảm hứng từ sự tiện lợi và đơn giản của chư...

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...

ManhDanBlogs