Laravel Eloquent Relationships | Laravel One to Many Eloquent Relationship Tutorial
One to Many relationships will use when one table is associated with multiple tables. For example, a post may have multiple comments. one to many eloquent relationships in laravel example.
So in this tutorial, you can understand how to create migration with a foreign key schema for one to many relationships, use sync with a pivot table, create records, get all data, delete, update, and everything related to one to many relationships.
In this example, I will create a “posts” table and “comments” table. both tables are connected with each other. now we will create one 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 below the screen.
One to Many Relationship will use “hasMany()” and “belongsTo()” for relation.
Create Migrations
Now we have to create a migration of the “posts” and “comments” table. we will also add a foreign key with the posts table. so let’s create like as below:
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');
});
Create Models
Here, we will create Post and Comment table model. we will also use “hasMany()” and “belongsTo()” for a relationship of both models.
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);
}
}
Retrieve Records
$post = Post::find(1);
$comments = $post->comments;
dd($comments);
$comment = Comment::find(1);
$post = $comment->post;
dd($post);
Create Records
$post = Post::find(1);
$comment = new Comment;
$comment->comment = "Hi rajtechnologies.com";
$post = $post->comments()->save($comment);
$post = Post::find(1);
$comment1 = new Comment;
$comment1->comment = "Hi rajtechnologies.com Comment 1";
$comment2 = new Comment;
$comment2->comment = "Hi rajtechnologies.com Comment 2";
$post = $post->comments()->saveMany([$comment1, $comment2]);
$comment = Comment::find(1);
$post = Post::find(2);
$comment->post()->associate($post)->save();
Post a Comment