Relationships sử dụng hasOne, belongsTo (ok)

https://www.youtube.com/watch?v=m0IsbkfONL4

Ví dụ 1:

app\User.php

public function address() {
    return $this->hasOne(Address::class);
}

routes\web.php

Route::get('/user', function(){
  $users = \App\User::all();
   return view('users.index',compact('users'));
});

resources\views\users\index.blade.php

@extends('layouts.app')
@section('content')
<div class="row justify-content-center">
	<div class="col-md-8">
		<div class="card">
			@foreach ($users as $user)
				<h2>{{$user->name}}</h2>
				<p>{{$user->address->country}}</p>
			@endforeach
		</div>
	</div>
</div>
@endsection

app\Address.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Address extends Model
{
    protected $fillable = [
        'user_id', 'country'
    ];
}

database\migrations\2014_10_12_000000_create_users_table.php

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

database\migrations\2020_08_06_083302_create_addresses_table.php

public function up()
{
    Schema::create('addresses', function (Blueprint $table) {
        $table->id();
        $table->bigInteger('user_id');
        $table->string("country");
        $table->timestamps();
    });
}

Kết quả:

Ví dụ 2:

C:\xampp\htdocs\hanam.com\app\Http\Controllers\HomeController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller {
  /**
   * Create a new controller instance.
   *
   * @return void
   */
  public function __construct() {
    $this->middleware('auth');
  }
  /**
   * Show the application dashboard.
   *
   * @return \Illuminate\Contracts\Support\Renderable
   */
  public function index() {
    return view('home');
  }
}

C:\xampp\htdocs\hanam.com\app\Address.php

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Address extends Model {
  protected $fillable = [
    'user_id', 'country',
  ];
}

C:\xampp\htdocs\hanam.com\app\User.php

<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
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',
  ];
  /**
   * The attributes that should be cast to native types.
   *
   * @var array
   */
  protected $casts = [
    'email_verified_at' => 'datetime',
  ];
  public function address() {
    return $this->hasOne(Address::class);
  }
}

C:\xampp\htdocs\abc\index.blade.php

@extends('layouts.app');
@section('content')
<div class="row justify-content-center">
	<div class="col-md-8">
		<div class="card">
			@foreach ($users as $user)
				<h2>{{$user->name}}</h2>
				<p>{{$user->address->country}}</p>
			@endforeach
		</div>
	</div>
</div>
@endsection

C:\xampp\htdocs\hanam.com\routes\web.php

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
  return view('welcome');
});
Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');
// Route::get('/user', function(){
//   factory(\App\User::class,5)->create();
// });
Route::get('/user', function(){
 $users = \App\User::all();
 return view('users.index',compact('users'));
});

Ví dụ 3: sử dụng belongsTo

C:\xampp\htdocs\hanam.com\app\Address.php

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Address extends Model {
  protected $fillable = [
    'user_id', 'country',
  ];
  public function user() {
  	return $this->belongsTo(User::class);
  }
}

C:\xampp\htdocs\hanam.com\resources\views\users\index.blade.php

@extends('layouts.app')
@section('content')
<div class="row justify-content-center">
	<div class="col-md-8">
		<div class="card">
			{{-- @foreach ($users as $user)
				<h2>{{$user->name}}</h2>
				<p>{{$user->address->country}}</p>
			@endforeach --}}
			@foreach ($addresses as $address)
				<h2>{{$address->country}}</h2>
				<p>{{$address->user->name}}</p>
			@endforeach
		</div>
	</div>
</div>
@endsection

C:\xampp\htdocs\hanam.com\app\User.php

<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
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',
  ];
  /**
   * The attributes that should be cast to native types.
   *
   * @var array
   */
  protected $casts = [
    'email_verified_at' => 'datetime',
  ];
  public function address() {
    return $this->hasOne(Address::class);
  }
}

C:\xampp\htdocs\hanam.com\routes\web.php

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
 */

Route::get('/', function () {
  return view('welcome');
});
Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');
// Route::get('/user', function(){
//   factory(\App\User::class,5)->create();
// });
Route::get('/user', function () {
	// $user  = factory(\App\User::class)->create();
	// \App\Address::create([
	// 	"user_id" => $user->id,
	// 	"country" => "Ha Nam 10"
	// ]);
	// $user->address()->create([
	// 	"country" => "Ha Nam 9"
	// ]);
  // $users = \App\User::all();
  $addresses = \App\Address::all();
  return view('users.index', compact('addresses'));
});

Last updated