Laravel One to Many Relationship
Laravel One to Many Relationship
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string("name");
$table->timestamps();
});
$table->increments('id');
$table->string("name");
$table->timestamps();
});
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('post_id');
$table->string("comment");
$table->timestamps();
$table->foreign('post_id')->references('id')->on('posts')
->onDelete('cascade');
});
$table->increments('id');
$table->unsignedInteger('post_id');
$table->string("comment");
$table->timestamps();
$table->foreign('post_id')->references('id')->on('posts')
->onDelete('cascade');
});
- Create Model :-
<?php
namespace App;
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
$post = $comment->post;
dd($post);
class Post extends Model
{
public function comments()
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public function post()
{
return $this->belongsTo(Post::class);
}
}
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public function post()
{
return $this->belongsTo(Post::class);
}
}
$comment = Comment::find(1);
$post = $comment->post;
dd($post);
$post = Post::find(1);
$comment = new Comment;
$comment->comment = "Hi Jaydeep";
$post = $post->comments()->save($comment);
$comment = new Comment;
$comment->comment = "Hi Jaydeep";
$post = $post->comments()->save($comment);
$post = Post::find(1);
$comment1 = new Comment;
$comment1->comment = "Hi Jaydeep";
$comment2 = new Comment;
$comment2->comment = "This is one to many relation.";
$post = $post->comments()->saveMany([$comment1, $comment2]);
$comment1 = new Comment;
$comment1->comment = "Hi Jaydeep";
$comment2 = new Comment;
$comment2->comment = "This is one to many relation.";
$post = $post->comments()->saveMany([$comment1, $comment2]);

Very useful
ReplyDeletetest
ReplyDelete