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à users và phones với cấu trúc cơ sở dữ liệu như sau:

One to One Relationship sẽ sử dụng "hasOne()" và "belongsTo()" cho mối quan hệ.

Tạo Migrations

Bây giờ chúng ta phải tạo migrate cho bảng users, bảng phones và thêm foreign key với bảng users. Vì vậy, bạn hãy tạo như hướng dẫn dưới đây:

Migration bảng users

Schema::create('users', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('email')->unique();
    $table->timestamp('email_verified_at')->nullable();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
});

Migration bảng phones

Schema::create('phones', function (Blueprint $table) {
    $table->id();
    $table->unsignedBigInteger('user_id');
    $table->string('phone');
    $table->timestamps();
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});

Tạo Models

Ở đây, chúng ta sẽ tạo model bảng users và phones. Chúng ta cũng sẽ sử dụng "hasOne ()" và "belongsTo()" cho mối quan hệ của cả hai model.

Model bảng users

<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * Get the phone record associated with the user.
     */
    public function phone()
    {
        return $this->hasOne(Phone::class);
    }
}

Model bảng phones

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

class Phone extends Model
{
    /**
     * Get the user that owns the phone.
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

Truy vấn dữ liệu

$phone = User::find(1)->phone;
dd($phone);
$user = Phone::find(1)->user;
dd($user);

Tạo mới dữ liệu

$user = User::find(1);
$phone = new Phone;
$phone->phone = '9429343852';
$user->phone()->save($phone);
$phone = Phone::find(1);
$user = User::find(10);
$phone->user()->associate($user)->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 Socialite Login With Facebook

Laravel Socialite Login With Facebook

Ngoài xác thực dựa trên biểu mẫu điển hình, Laravel cũng cung cấp một cách đơn giản và thuận tiện để sử dụng Laravel Socialite để xác thực với các nhà cung cấp OAuth. Socialite hiện hỗ trợ xác thực qu...

Integrating OpenAI in Laravel

Integrating OpenAI in Laravel

OpenAI OpenAI là một phòng thí nghiệm nghiên cứu trí tuệ nhân tạo (AI) của Mỹ bao gồm tổ chức phi lợi nhuận OpenAI Incorporated (OpenAI Inc.) và công ty con hoạt động vì lợi nhuận OpenAI Limited Par...

Simplify Your Laravel Workflow with Laravel Pint

Simplify Your Laravel Workflow with Laravel Pint

Laravel Pint là gì? Laravel Pint là một công cụ sửa đổi mã nguồn của bạn để mã nguồn của bạn tuân thủ theo các tiêu chuẩn. Nói một cách khác, Laravel Pint sẽ quét toàn bộ mã nguồn của bạn, phát...

Laravel One to Many Polymorphic Relationship

Laravel One to Many Polymorphic Relationship

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

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 Accessor and Mutator

Laravel Accessor and Mutator

Trong bài viết này, tôi sẽ hướng dẫn các bạn cách để format các Eloquent Attributes bằng cách sử dụng tính năng Laravel Accessors and Mutators. Accessors được sử dụng để format các thuộc tính khi 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...

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

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

ManhDanBlogs