Laravel Eloquent Relationships Tutorial From Scratch (ok)

https://www.itsolutionstuff.com/post/laravel-eloquent-relationships-tutorial-from-scratchexample.html

Đọc thêm: https://c-i-ph-n-m-m-tr-n-ubuntu-c-n-thi.gitbook.io/learn-lavarel/sau-khi-gap-cac-loi-phat-sinh-migration-gio-chung-ta-co-ban-full-ok

Ví dụ 1: làm dữ liệu thêm foreign (ok)

Một điều đặc biệt chú ý là khi tạo khóa phụ thì bảng phục phải được sinh ra trước Giải pháp 👍ta thay đổi thời gian ở tên file ví dụ:

2022_05_10_163257_create_countries_table.php thay đổi thành 2020_05_10_163257_create_countries_table.php

Ví dụ 2: làm dữ liệu thêm foreign (ok)

Chú ý: Cách này tạo ra nhiều lỗi khi migrate 😒

C:\xampp\htdocs\test\database\migrations\2014_10_12_000000_create_users_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration {
  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up() {
    Schema::create('users', function (Blueprint $table) {
      $table->bigIncrements('id'); // Mặc định cái này là bigteger không âm do đó để không bị lỗi khóa phục cũng phải cùng loại :)
      $table->string('name');
      $table->string('email')->unique();
      $table->timestamp('email_verified_at')->nullable();
      $table->string('password');
      $table->rememberToken();
      $table->timestamps();
      $table->bigInteger('country_id')->unsigned();
      $table->foreign('country_id')->references('id')->on('users')->onDelete('cascade');
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down() {
    Schema::dropIfExists('users');
  }
}

C:\xampp\htdocs\test\database\migrations\2022_05_10_163257_create_countries_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCountriesTable extends Migration {
  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up() {
    Schema::create('countries', function (Blueprint $table) {
      $table->bigIncrements('id');
      $table->string('name');
      $table->timestamps();
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down() {
    Schema::dropIfExists('countries');
  }
}

C:\xampp\htdocs\test\database\migrations\2022_05_10_163113_create_posts_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration {
  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up() {
    Schema::create('posts', function (Blueprint $table) {
      $table->bigIncrements('id');
      $table->string("name");
      $table->bigInteger('user_id')->unsigned();
      $table->timestamps();
      $table->foreign('user_id')->references('id')->on('posts')->onDelete('cascade');
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down() {
    Schema::dropIfExists('posts');
  }
}

Laravel Eloquent Relationships Tutorial From Scratch

As we know database table is almost related to another database table. but when you are working on retrieve data, create data or etc task. you have to use a join or something on every SQL query. So it takes time and also we have to write lots of database query. But in laravel Eloquent Model Relationship we can easily make in relation by using their types.

Why we should use laravel model relationship, So I want to give one example for this. If you have a "users" table and also you have "user_addresses" table. both tables are connected with each other using a foreign key. There are several records in users table and also more records in your address table. If you didn't use laravel eloquent relationship then you can get all address using "join" like as below:

Basic Model Query:

$userAddresses = User::select("users.*", "user_addresses.*")                 ->join("user_addresses", "user_addresses.id_user", "=", "users.id")                 ->where("users.id", 1)                 ->get(); dd($userAddresses);

As you can above laravel query, you have to write long query, right now it is not big, but when you have more tables connected with users table then it can be more complected, so if we use laravel Relationship then you can do it just simple and you don't require to write every time join and anything, laravel will manage it. So you can write this way:

Model Query Using Relationship:

Read Also: Laravel One to One Eloquent Relationship Tutorial

$userAddresses = User::find(1); dd($userAddresses->address);

As you can see how it is simple, so i can say, we have to use laravel relationship.

In this tutorial, i will explain every types with how to insert data with relation model and how to get records from database table using model. i will also give example with table migration, model, retrieve and create new records. You have to just read and you will understand how it is working on all types of relationships in laravel. You can easily use order by, filter, where condition, delete, create, update, group by, get all, get count, save etc laravel methods.

Now as bellow i listed all laravel model relationships types and you can click on it and read in details of each types.

*** Click On it and Read in Details of RelationShip types:

Last updated