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

Laravel UI Custom Email Verification Template

Laravel UI Custom Email Verification Template

Nếu bạn đang dùng thư viện laravel/ui để làm các chức năng liên quan đến authentication, và trong dự án của bạn, bạn cần thay đổi template email verification thay vì sử dụng template email verificatio...

Laravel Facades

Laravel Facades

Facade là gì? Chúng ta có thể hiểu Facade là mặt tiền và mặt trước của một tòa nhà hay bất cứ thứ gì. Tầm quan trọng của Facade là chúng có thể dễ nhận thấy và nổi bật hơn, tương tự như vậy, thì...

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

Integrating elFinder into TinyMCE 6 in Laravel

Integrating elFinder into TinyMCE 6 in Laravel

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ười d...

Laravel User Authentication

Laravel User Authentication

Trong hướng dẫn này, tôi sẽ hướng dẫn bạn xây dựng chức năng đăng nhập trong Laravel. Công bằng mà nói thì bạn có thể sử dụng Laravel UI hoặc JetStream để tự động tạo ra chức năng đăng nhập trong Lara...

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

Integrating AI Assistant with CKEditor 5 in Laravel using Vite

Integrating AI Assistant with CKEditor 5 in Laravel using Vite

OpenAI OpenAI là một công ty nghiên cứu và triển khai trí tuệ nhân tạo, nổi tiếng với việc phát triển các mô hình AI tiên tiến. Mục tiêu của OpenAI là đảm bảo rằng trí tuệ nhân tạo tổng quát (AGI...

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

ManhDanBlogs