Sử dụng quan hệ Many to Many dùng theo một Model mà ta tự định nghĩa (ok)

https://viblo.asia/p/tim-hieu-eloquent-trong-laravel-phan-2-relationship-RnB5pym7KPG

Ví dụ đã hoàn thành:

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 = \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();
  // \App\Tag::create([
  //   'name' => 'Lavarel'
  // ]);
  // \App\Tag::create([
  //   'name' => 'PHP'
  // ]);
  // \App\Tag::create([
  //   'name' => 'Javascript'
  // ]);
  // \App\Tag::create([
  //   'name' => 'VueJs'
  // ]);
  // $tag = \App\Tag::first();
  // $post = \App\Post::first();
  // $post = \App\Post::with('tags')->first();
  // $post->tags()->attach($tag);
  // $post->tags()->attach([1,2,3,4]); 
  // $post->tags()->sync([1,2,3,4]);
  // $post->tags()->detach([1]);
  $post  = \App\Post::first();
  $posts = \App\Post::with(['user','tags'])->get();
  // $post->tags()->attach([
  //   1 => [
  //     'status' => 'approved'
  //   ]
  // ]);
  // dd($post->tags->first()->pivot->status);
  dd($post->tags);
  // Post::delete();
	return view('posts.index',compact('posts'));
});
Route::get('/tags', function () {
  $tags = \App\Tag::with("posts")->get();
  return view('tags.index',compact('tags'));
});

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

@extends('layouts.app')
@section('content')
<div class="row justify-content-center">
	<div class="col-md-8">
		<div class="card">
			@foreach ($posts as $post)
				<h1>{{$post->title}}</h1>
				<p>{{ $post->user->name }}</p>
				<ul>
					<li>
						@foreach ($post->tags as $tag)
							<li>{{$tag->name}}&nbsp;{{ $tag->pivot->created_at->diffForHumans() }}</li>
						@endforeach
					</li>
				</ul>
			@endforeach
		</div>
	</div>
</div>
@endsection

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

<?php
namespace App;
use Illuminate\Database\Eloquent\Relations\Pivot;
class PostTag extends Pivot {
  protected $table = 'post_tag';
  public static function boot() {
  	parent::boot();
  	static::created(function($item) {
  		dd($item);
  	});
  }
}

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

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model {
  protected $fillable = ['user_id','title'];
  public function user() {
  	return $this->belongsTo(User::class)->withDefault([
  		'name' => 'Guest User'
  	]);
  }
  public function tags() {
  	// return $this->belongsToMany(Tag::class,'post_tag','post_id','tag_id');
  	// return $this->belongsToMany(Tag::class)->withTimestamps();
    return $this->belongsToMany(Tag::class)
    ->using(PostTag::class)
    ->withTimestamps()
    ->withPivot('status');
  }
}

Kết quả:

Nếu như chúng ta muốn quan hệ Many to Many dùng theo một model mà ta tự định nghĩa nào đó, không theo quy tắc mà Laravel định nghĩa ra thì chúng ta sẽ làm như sau

namespace App;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    public function products()
    {
        return $this->belongsToMany(Product::class)->using(Detail::class);
    }
}
Và khi định nghĩa Detail model thì chúng ta nhớ extend Illuminate\Database\Eloquent\Relations\Pivot vào nhé

<?php

namespace App;

use Illuminate\Database\Eloquent\Relations\Pivot;

class Detail extends Pivot
{
    //
}
Thật là dễ dàng đúng không nào 

Last updated