When one table is linked to numerous tables, a one-to-many relationship is used. A post, for example, could include many comments. In the examples of Laravel 6, Laravel 7, Laravel 8, and Laravel 9, there is an eloquent one-to-many relationship.
So, in this tutorial, you'll learn how to establish a one-to-many relationship migration using a foreign key schema, how to utilise sync with a pivot table, how to add records, obtain all data, delete, update, and everything else related to one-to-many relationships.
I'll make a "posts" table and a "comments" table in this example. Both tables are linked to one another. Using the Laravel Eloquent Model, we'll now construct one-to-many relationships with each other. We'll start with database migration, then move on to modeling, retrieving records, and finally creating records.
"hasMany()" and "belongsTo()" will be used for relation in a One to Many Relationship.
1. Create Migrations
The "posts" and "comments" tables must now be migrated. With the posts table, we'll also add a foreign key. So, let's make something like this:
Posts table migration
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string("name");
$table->timestamps();
});
Comments table migration
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->integer('post_id')->unsigned();
$table->string("comment");
$table->timestamps();
$table->foreign('post_id')->references('id')->on('posts')
->onDelete('cascade');
});
2. Create Models
We'll make a Post and Comment table model here. For both models' relationships, we'll use "hasMany()" and "belongsTo()."
Post Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
/**
* Get the comments for the blog post.
*/
public function comments()
{
return $this->hasMany(Comment::class);
}
}
?>
Comment Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
/**
* Get the post that owns the comment.
*/
public function post()
{
return $this->belongsTo(Post::class);
}
}
?>
3. Retrieve Records
$post = Post::find(1);
$comments = $post->comments;
dd($comments);
$comment = Comment::find(1);
$post = $comment->post;
dd($post);
4. Create Records
$post = Post::find(1);
$comment = new Comment;
$comment->comment = "Hi CodeSolutionStuff";
$post = $post->comments()->save($comment);
$post = Post::find(1);
$comment1 = new Comment;
$comment1->comment = "Hi CodeSolutionStuff Comment 1";
$comment2 = new Comment;
$comment2->comment = "Hi CodeSolutionStuff Comment 2";
$post = $post->comments()->saveMany([$comment1, $comment2]);
$comment = Comment::find(1);
$post = Post::find(2);
$comment->post()->associate($post)->save();
I hope you will like the content and it will help you to learn Laravel One to Many Eloquent Relationship
If you like this content, do share.