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

Trong ví dụ này, tôi sẽ tạo bảng "posts" và bảng "comments". cả hai bảng đều được liên kết với nhau. Bây giờ chúng ta sẽ tạo One to Many 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 Relationship sẽ sử dụng "hasMany()" and "belongsTo()" cho mối quan hệ.

Tạo Migrations

Bây giờ chúng ta phải tạo migrate cho bảng posts, bảng comments và thêm foreign key với bảng posts. 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 comments

Schema::create('comments', function (Blueprint $table) {
    $table->id();
    $table->unsignedBigInteger('post_id');
    $table->string("comment");
    $table->timestamps();
    $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
});

Create Models

Tại đây, chúng ta sẽ tạo model bảng post và comment. Chúng ta cũng sẽ sử dụng "hasMany ()" và "belongsTo()" 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 the comments for the blog post.
     */
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}

Model bảng comments

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    /**
     * Get the post that owns the comment.
     */
    public function post()
    {
        return $this->belongsTo(Post::class);
    }
}

Truy vấn dữ liệu

$post = Post::find(1);
$comments = $post->comments;
dd($comments);
$comment = Comment::find(1);
$post = $comment->post;
dd($post);

Tạo mới dữ liệu

$post = Post::find(1);
$comment = new Comment;
$comment->comment = "Hi ManhDanBlog";
$post = $post->comments()->save($comment);
$post = Post::find(1);
 
$comment1 = new Comment;
$comment1->comment = "Hi ManhDanBlog Comment 1";
 
$comment2 = new Comment;
$comment2->comment = "Hi ManhDanBlog Comment 2";
 
$post = $post->comments()->saveMany([$comment1, $comment2]);
$comment = Comment::find(1);
$post = Post::find(2);
 
$comment->post()->associate($post)->save();

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 Export & Import CSV

Laravel Export & Import CSV

Trong bài viết này, tôi sẽ hướng dẫn các tạo cách Export hoặc Import CSV trong Laravel. Nhưng thay vì chỉ viết hàm đơn thuần trong PHP thì tôi sẽ hướng dẫn các tạo ra một Service trong Laravel bằng cá...

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

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

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

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

Laravel Scout Full Text Search With Meilisearch

Laravel Scout Full Text Search With Meilisearch

Laravel Scout cung cấp một giải pháp đơn giản, dựa trên trình điều khiển để thêm tìm kiếm Full Text vào các mô hình Eloquent của bạn. Khi sử dụng Eloquent, Scout sẽ tự động giữ chỉ mục tìm kiếm của bạ...

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

Laravel Middlewares

Laravel Middlewares

Middleware cung cấp một cơ chế thuận tiện để lọc các yêu cầu HTTP gửi đến ứng dụng bạn. Nó là một lớp trung gian nằm giữa request và controller. Bạn có thể thêm các xử lý logic trước khi gửi đến contr...

ManhDanBlogs