One To Many relationship hasMany và phương thức thêm vô cùng hay (ok)

https://www.youtube.com/watch?v=rb2Tf8zByRU&t=545s

0:56 hasMany()
7:25 optional() helper function
8:42 Default Models in belongsTo() relation: withDefault(); 
11:08 Querying Relationship Existence: has(), whereHas()
12:55 Querying Relationship Absence: doesntHave(), whereDoesntHave()

Ví dụ 1:

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);
  }
  public function addresses() {
    return $this->hasMany(Address::class); 
  }
}

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

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

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

Ví dụ 2:

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

Ví dụ 3: Kiểm tra nếu >= 2 posts thì in ra :)

Ví dụ 4: Lọc trong tiêu đề có cụm từ "Post 2" thì lấy ra bài viết.

Ví dụ 4:Kiểm tra xem tác giả nào chưa có bài viết

Last updated

Was this helpful?