DB 테이블의 1대다 연결 설정
Post has many Comment
Commnet belongs to Post
- hasMany()
- belongsTo()
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string("name");
$table->timestamps();
});
Schema::create('comments', function (Blueprint $table) {
$table->id();
$table->integer('post_id')->unsigned();
$table->string("comment");
$table->timestamps();
$table->foreign('post_id')->references('id')->on('posts')
->onDelete('cascade');
});
hasMany()
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function comments()
{
return $this->hasMany(App\Models\Comment::class);
}
}
belongsTo()
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public function post()
{
return $this->belongsTo(App\Models\Post::class);
}
}
조회하기
$post = Post::find(1);
$comments = $post->comments;
dd($comments);
$comment = Comment::find(1);
$post = $comment->post;
dd($post);
저장하기
$post = Post::find(1);
$comment = new Comment;
$comment->comment = "Hi ItSolutionStuff.com";
$post = $post->comments()->save($comment);
saveMany()
$post = Post::find(1);
$comment1 = new Comment;
$comment1->comment = "Hi ItSolutionStuff.com Comment 1";
$comment2 = new Comment;
$comment2->comment = "Hi ItSolutionStuff.com Comment 2";
$post = $post->comments()->saveMany([$comment1, $comment2]);
연결시키기 associate()
$comment = Comment::find(1);
$post = Post::find(2);
$comment->post()->associate($post)->save();
'Laravel' 카테고리의 다른 글
Laravel - 로컬개발 환경설정 (Homestead with VirtualBox) (0) | 2023.12.22 |
---|---|
Laravel - Middleware에 대해서 (0) | 2023.12.21 |
Laravel - CRUD 기본 코드 (0) | 2023.12.01 |
Laravel - Request 객체 다루기 (0) | 2023.11.21 |
Laravel Breeze 와 Laravel Jetstream 차이점. (0) | 2023.11.19 |