Laravel:Relations OneToMany,ManyToMany,OneToOne....
1. Relation "Un à Un" (One to One) - User et Profile
php artisan make:migration create_Utilisateurs_table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up()
{
Schema::create('Utilisateurs', function (Blueprint $table) {
$table->id();//id int primary key
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('Utilisateurs');
}
};
php artisan make:model Models\Utilisateur
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Utilisateur extends Model
{
protected $table = 'Utilisateurs';
protected $primaryKey = 'id';
public $timestamps = true;
protected $fillable = [
'name', 'email', 'password'
];
// Relation Un à Un : Un utilisateur a un seul profil
public function profile()
{
return $this->hasOne('App\Models\Profile');
//lorsque le model profile a primaryKey=id ,on n'as pas besoin de spécifier idProfile dans la relation has.. ,belongsTo...
}
}
php artisan make:migration create_profiles_table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up()
{
Schema::create('profiles', function (Blueprint $table) {
$table->id();
$table->foreignId('Utilisateur_id')->constrained();//permet de créer la foreign key Utilisateur_id qui references Utlisateur(id)
//constraint foreign key('Utilisateur_id') references Utilisateur(id)
//lorsque Utilisateur a primarykey=id ,pour déclarer une foreign key on appell Model_id dans ce cas Utilisateur_id
$table->text('bio')->nullable();
$table->string('avatar')->nullable();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('profiles');
}
};
php artisan make:model Models\Profile
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
protected $table = 'profiles';
protected $primaryKey = 'id';
public $timestamps = true;
protected $fillable = [
'Utilisateur_id', 'bio', 'avatar'
];
// Relation Un à Un inverse : Un profil appartient à un utilisateur
public function Utilisateur()
{
return $this->belongsTo('App\Models\Utilisateur');
}
}
2. Relation "Un à Plusieurs" (One to Many) - Author et Book
php artisan make:migration create_authors_table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up()
{
Schema::create('authors', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('authors');
}
};
php artisan make:model Models\Author
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Author extends Model
{
protected $table = 'authors';
protected $primaryKey = 'id';
public $timestamps = true;
protected $fillable = [
'name', 'email'
];
// Relation Un à Plusieurs : Un auteur peut avoir plusieurs livres
public function books()
{
return $this->hasMany('App\Models\Book');
}
}
php artisan make:migration create_books_table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up()
{
Schema::create('books', function (Blueprint $table) {
$table->id();
$table->foreignId('author_id')->constrained();
$table->string('title');
$table->text('description');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('books');
}
};
php artisan make:model Models\Book
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Book extends Model
{
protected $table = 'books';
protected $primaryKey = 'id';
public $timestamps = true;
protected $fillable = [
'author_id', 'title', 'description'
];
// Relation Un à Plusieurs inverse : Un livre appartient à un auteur
public function author()
{
return $this->belongsTo('App\Models\Author');
}
}
3. Relation "Plusieurs à Plusieurs" (Many to Many) - Student et Course
php artisan make:migration create_students_table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up()
{
Schema::create('students', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('students');
}
};
php artisan make:model Models\Student
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
protected $table = 'students';
protected $primaryKey = 'id';
public $timestamps = true;
protected $fillable = [
'name', 'email'
];
// Relation Plusieurs à Plusieurs : Un étudiant peut être inscrit à plusieurs cours
public function courses()
{
return $this->belongsToMany('App\Models\Course');
}
}
php artisan make:migration create_courses_table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up()
{
Schema::create('courses', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('description');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('courses');
}
};
php artisan make:model Models\Course
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Course extends Model
{
protected $table = 'courses';
protected $primaryKey = 'id';
public $timestamps = true;
protected $fillable = [
'title', 'description'
];
// Relation Plusieurs à Plusieurs inverse : Un cours peut avoir plusieurs étudiants
public function students()
{
return $this->belongsToMany('App\Models\Student');
}
}
4. Relation Polymorphe - Comment et Post
php artisan make:migration create_comments_table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up()
{
Schema::create('comments', function (Blueprint $table) {
$table->id();//id int primary key
$table->text('content');
$table->unsignedBigInteger('commentable_id');
$table->string('commentable_type');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('comments');
}
}
php artisan make:model Models\Comment
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
protected $table = 'comments';
protected $primaryKey = 'id';
public $timestamps = true;
protected $fillable = [
'content', 'commentable_id', 'commentable_type'
];
// Relation Polymorphe : Un commentaire peut appartenir à un post ou à une vidéo
public function commentable()
{
return $this->morphTo();
}
};
php artisan make:migration create_posts_table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('content');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('posts');
}
};
php artisan make:model Models\Post
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $table = 'posts';
protected $primaryKey = 'id';
public $timestamps = true;
protected $fillable = [
'title', 'content'
];
// Relation Polymorphe inverse : Un post peut avoir plusieurs commentaires
public function comments()
{
return $this->morphMany('App\Models\Comment', 'commentable');
}
}
la Relation Polymorphe - Video
php artisan make:migration create_videos_table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up()
{
Schema::create('videos', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('description');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('videos');
}
};
php artisan make:model Models\Video
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Video extends Model
{
protected $table = 'videos';
protected $primaryKey = 'id';
public $timestamps = true;
protected $fillable = [
'title', 'description'
];
// Relation Polymorphe inverse : Une vidéo peut avoir plusieurs commentaires
public function comments()
{
return $this->morphMany('App\Models\Comment', 'commentable');
}
}
Utilisation des Relations
<?
// Création d'un utilisateur
$Utilisateur = Utilisateur::create([
'name' => 'John Doe',
'email' => 'john@example.com',
'password' => bcrypt('secret'),
]);
// Création d'un profil pour l'utilisateur
$profile = $Utilisateur->profile()->create([
'bio' => 'A passionate Laravel developer.',
'avatar' => 'avatar.jpg',
]);
Exemple d'Utilisation de la Relation Un à Plusieurs
php
Copy code
// Création d'un auteur
$author = Author::create([
'name' => 'Jane Author',
'email' => 'jane@example.com',
]);
// Ajout de plusieurs livres pour l'auteur
$book1 = $author->books()->create([
'title' => 'Book 1',
'description' => 'Description for Book 1',
]);
$book2 = $author->books()->create([
'title' => 'Book 2',
'description' => 'Description for Book 2',
]);
Exemple d'Utilisation de la Relation Plusieurs à Plusieurs
php
Copy code
// Création d'un étudiant
$student = Student::create([
'name' => 'Alice Student',
'email' => 'alice@example.com',
]);
// Inscrit l'étudiant à plusieurs cours
$course1 = Course::create([
'title' => 'Course 1',
'description' => 'Description for Course 1',
]);
$course2 = Course::create([
'title' => 'Course 2',
'description' => 'Description for Course 2',
]);
$student->courses()->attach([$course1->id, $course2->id]);
Exemple d'Utilisation de la Relation Polymorphe
php
Copy code
// Création d'un post
$post = Post::create([
'title' => 'My First Post',
'content' => 'This is the content of my first post.',
]);
// Ajout de commentaires au post
$comment1 = $post->comments()->create([
'content' => 'Great post!',
]);
$comment2 = $post->comments()->create([
'content' => 'I enjoyed reading this.',
]);
// Création d'une vidéo
$video = Video::create([
'title' => 'Laravel Tutorial',
'description' => 'A tutorial on Laravel basics.',
]);
// Ajout de commentaires à la vidéo
$comment3 = $video->comments()->create([
'content' => 'Very helpful tutorial.',
]);
$comment4 = $video->comments()->create([
'content' => 'Thanks for sharing!',
]);