Bên này sử dụng cho các ví dụ One to One, One to Many
C:\xampp\htdocs\test\routes\web.php
<?phpuseIlluminate\Support\Facades\Route;useApp\Http\Controllers\UserController;useApp\Http\Controllers\PostController ;/*|--------------------------------------------------------------------------| 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('test', [UserController::class,'index']);// One to OneRoute::get('/', [PostController::class,'index']);// One to Many, Many To Many
Ví dụ 1: cho mối quan hệ 1-1
C:\xampp\htdocs\test\app\Http\Controllers\UserController.php
<?phpnamespaceApp\Models;useIlluminate\Database\Eloquent\Factories\HasFactory;useIlluminate\Database\Eloquent\Model;classRoleextendsModel {useHasFactory;/** * The users that belong to the role. */publicfunctionusers() {return$this->belongsToMany(User::class,'role_user'); }}
C:\xampp\htdocs\test\app\Models\User.php
<?phpnamespaceApp\Models;useIlluminate\Database\Eloquent\Factories\HasFactory;useIlluminate\Foundation\Auth\Useras Authenticatable;useIlluminate\Notifications\Notifiable;useLaravel\Sanctum\HasApiTokens;classUserextendsAuthenticatable {useHasApiTokens,HasFactory,Notifiable;/** * The attributes that are mass assignable. * * @vararray<int, string> */protected $fillable = ['name','email','password', ];/** * The attributes that should be hidden for serialization. * * @vararray<int, string> */protected $hidden = ['password','remember_token', ];/** * The attributes that should be cast. * * @vararray<string, string> */protected $casts = ['email_verified_at'=>'datetime', ];/** * Get the phone associated with the user. * * Syntax: return $this->hasOne(Phone::class, 'foreign_key', 'local_key'); * * Example: return $this->hasOne(Phone::class, 'user_id', 'id'); */publicfunctionphone() {return$this->hasOne(Phone::class,'user_id','id'); }/** * The roles that belong to the user. */publicfunctionroles() {return$this->belongsToMany(Role::class,'role_user'); }}
<?phpnamespaceApp\Models;useIlluminate\Database\Eloquent\Factories\HasFactory;useIlluminate\Foundation\Auth\Useras Authenticatable;useIlluminate\Notifications\Notifiable;useLaravel\Sanctum\HasApiTokens;classUserextendsAuthenticatable {useHasApiTokens,HasFactory,Notifiable;/** * The attributes that are mass assignable. * * @vararray<int, string> */protected $fillable = ['name','email','password', ];/** * The attributes that should be hidden for serialization. * * @vararray<int, string> */protected $hidden = ['password','remember_token', ];/** * The attributes that should be cast. * * @vararray<string, string> */protected $casts = ['email_verified_at'=>'datetime', ];/** * The roles that belong to the user. */publicfunctionroles() {return$this->belongsToMany(Role::class,'role_user'); }}
Ví dụ 2.4.1: Many To Many lấy giá trị trung gian (Theo mặc định, chỉ có các keys sẽ có mặt trên các pivot object.) đọc thêm
Kết quả:
Nếu bạn muốn bảng pivot của bạn tự động có created_at và updated_at timestamps, sử dụng các phương thức Timestamps vào trong định nghĩa của mối quan hệ:
<?phpuseApp\Http\Controllers\UserController;useIlluminate\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 () {returnview('welcome');});Route::get('/user', [UserController::class,'getRoles']);
Ví dụ 2.4.2: Many To Many lọc giá trị trong bảng trung gian (Đọc thêm)
C:\xampp8\htdocs\testauth\app\Models\User.php
<?phpnamespaceApp\Models;// use Illuminate\Contracts\Auth\MustVerifyEmail;useIlluminate\Database\Eloquent\Factories\HasFactory;useIlluminate\Foundation\Auth\Useras Authenticatable;useIlluminate\Notifications\Notifiable;useLaravel\Sanctum\HasApiTokens;classUserextendsAuthenticatable{useHasApiTokens,HasFactory,Notifiable;/** * The attributes that are mass assignable. * * @vararray<int, string> */protected $fillable = ['name','email','password', ];/** * The attributes that should be hidden for serialization. * * @vararray<int, string> */protected $hidden = ['password','remember_token', ];/** * The attributes that should be cast. * * @vararray<string, string> */protected $casts = ['email_verified_at'=>'datetime', ];/** * The roles that belong to the user. */publicfunctionroles() { return $this->belongsToMany(Role::class,'role_user','user_id','role_id')->withPivot('created_at')->wherePivotIn('created_at', ['2023-01-04 10:35:33', '2023-01-04 10:35:32']);
}}
Kết quả:
Laravel 9 Many to Many Eloquent Relationship Tutorial
By Hardik Savani March 28, 2022 Category : LaravelPauseUnmuteLoaded: 2.69%FullscreenHi,
Today our leading topic is many to many relationship laravel 9. I would like to share with you laravel 9 many to many relationship example. This tutorial will give you a simple example of laravel 9 belongstomany tutorial. This tutorial will give you simple example of laravel 9 many to many sync.
So in this tutorial, you can understand how to create many-to-many relationships with migration with a foreign key schema for one to many relationships, use sync with a pivot table, create records, attach records, get all records, delete, update, where condition and everything related to many to many relationship.
In this example, i will create "users", "roles" and "role_user" tables. each table is connected with each other. now we will create many to many relationships with each other by using the laravel Eloquent Model. We will first create database migration, then model, retrieve records and then how to create records too. So you can also see the database table structure on the below screen.
Many to Many Relationship will use "belongsToMany()" for relation.
Create Migrations:
Now we have to create migration of "users", "roles" and "role_user" table. we will also add foreign key with users and roles table. so let's create like as below:
users table migration:
<?php use Illuminate\Database\Migrations\Migration;use Illuminate\Database\Schema\Blueprint;use Illuminate\Support\Facades\Schema; return new class extends Migration{ /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email')->unique(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->rememberToken(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('users'); }};
roles table migration:
<?php use Illuminate\Database\Migrations\Migration;use Illuminate\Database\Schema\Blueprint;use Illuminate\Support\Facades\Schema; return new class extends Migration{ /** * Run the migrations. * * @return void */ public function up() { Schema::create('roles', function (Blueprint $table) { $table->id(); $table->string('name'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('roles'); }};
role_user table migration:
<?php use Illuminate\Database\Migrations\Migration;use Illuminate\Database\Schema\Blueprint;use Illuminate\Support\Facades\Schema; return new class extends Migration{ /** * Run the migrations. * * @return void */ public function up() { Schema::create('role_user', function (Blueprint $table) { $table->foreignId('user_id')->constrained('users'); $table->foreignId('role_id')->constrained('roles'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('role_user'); }};
Create Models:
Here, we will create User, Role and UserRole table model. we will also use "belongsToMany()" for relationship of both model.
User Model:
<?php namespace App\Models; use Illuminate\Contracts\Auth\MustVerifyEmail;use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Foundation\Auth\User as Authenticatable;use Illuminate\Notifications\Notifiable;use Laravel\Sanctum\HasApiTokens; class User extends Authenticatable{ use HasApiTokens, HasFactory, Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', ]; /** * The attributes that should be hidden for serialization. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; /** * The attributes that should be cast. * * @var array */ protected $casts = [ 'email_verified_at' => 'datetime', ]; /** * The roles that belong to the user. */ public function roles() { return $this->belongsToMany(Role::class, 'role_user'); }}
Role Model:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Database\Eloquent\Model; class Role extends Model{ use HasFactory; /** * The users that belong to the role. */ public function users() { return $this->belongsToMany(User::class, 'role_user'); }}
UserRole Model:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Database\Eloquent\Model; class UserRole extends Model{ use HasFactory; }