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
<?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();
$users = \App\User::with('addresses')->get();
return view('users.index', compact('users'));
});
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 --}}
@foreach ($users as $user)
<h2>{{$user->name}}</h2>
@foreach ($user->addresses as $address)
<p>{{$address->country}}</p>
@endforeach
@endforeach
</div>
</div>
</div>
@endsection
C:\xampp\htdocs\hanam.com\app\Address.php
$users[0]->addresses()->create
<?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);
}
}
Ví dụ 2:
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();
$users = \App\User::with('addresses')->get();
$users[0]->addresses()->create([
"country" => "Ha Nam 4"
]);
return view('users.index', compact('users'));
});
Ví dụ 3: Kiểm tra nếu >= 2 posts thì in ra :)
<?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();
// $users = \App\User::with('addresses')->get();
// $users = \App\User::get();
// Hoặc dùng cách khác
// $users = \App\User::with('posts')->get();
$users = \App\User::has('posts','>=',2)->with('posts')->get();
// $users[0]->posts()->create([
// "title" => "Post 1 Test"
// ]);
// $users[2]->posts()->create([
// "title" => "Post 2 Test"
// ]);
return view('users.index', compact('users'));
});
Route::get('/posts', function () {
// \App\Post::create([
// 'user_id' => 1,
// 'title' => 'Post title 1'
// ]);
$posts = \App\Post::get();
return view('posts.index',compact('posts'));
});
Ví dụ 4: Lọc trong tiêu đề có cụm từ "Post 2" thì lấy ra bài viết.
<?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();
// $users = \App\User::with('addresses')->get();
// $users = \App\User::get();
// Hoặc dùng cách khác
// $users = \App\User::with('posts')->get();
// $users = \App\User::has('posts','>=',2)->with('posts')->get();
$users = \App\User::whereHas('posts',function($query) {
$query->where('title','like','%Post 2%');
})->with('posts')->get();
// $users[0]->posts()->create([
// "title" => "Post 1 Test"
// ]);
// $users[2]->posts()->create([
// "title" => "Post 2 Test"
// ]);
return view('users.index', compact('users'));
});
Route::get('/posts', function () {
// \App\Post::create([
// 'user_id' => 1,
// 'title' => 'Post title 1'
// ]);
$posts = \App\Post::get();
return view('posts.index',compact('posts'));
});
Ví dụ 4:Kiểm tra xem tác giả nào chưa có bài viết
<?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();
// $users = \App\User::with('addresses')->get();
// $users = \App\User::get();
// Hoặc dùng cách khác
// $users = \App\User::with('posts')->get();
// $users = \App\User::has('posts','>=',2)->with('posts')->get();
// $users = \App\User::whereHas('posts',function($query) {
// $query->where('title','like','%Post 2%');
// })->with('posts')->get();
$users = \App\User::doesntHave('posts')->with('posts')->get();
// $users[0]->posts()->create([
// "title" => "Post 1 Test"
// ]);
// $users[2]->posts()->create([
// "title" => "Post 2 Test"
// ]);
return view('users.index', compact('users'));
});
Route::get('/posts', function () {
// \App\Post::create([
// 'user_id' => 1,
// 'title' => 'Post title 1'
// ]);
$posts = \App\Post::get();
return view('posts.index',compact('posts'));
});
PreviousNói về trường hợp mặc định về phương thức trùng với tên bảng nó sẽ quyết định id (ok)NextMột chú ý đặc biệt về cách đặt key cho belongsToMany (ok)
Last updated