Back-End/Laravel
[Laravel] 3장 Eloquent ORM을 이용한 데이터베이스 쿼리 및 관계 설정
Tinkies
2025. 3. 1. 03:20
1. 모델 생성
Laravel의 Eloquent ORM을 사용해 데이터베이스 쿼리 및 관계 설정을 하는 방법을 설명합니다. Eloquent는 Laravel의 ORM으로, 데이터베이스와의 상호작용을 쉽게 해줍니다. 먼저 Eloquent 모델을 생성합니다.
php artisan make:model Post -m
php artisan make:model Comment -m
2. 마이그레이션 설정
database/migrations 폴더에 생성된 마이그레이션 파일을 열어 게시글과 댓글 테이블을 설정합니다.
- create_posts_table.php
public function up(): void
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('content');
$table->timestamps();
});
}
- create_comments_table.php
public function up()
{
Schema::create('comments', function (Blueprint $table) {
$table->id();
$table->foreignId('post_id')->constrained()->onDelete('cascade');
$table->text('content');
$table->timestamps();
});
}
마이그레이션을 실행합니다.
php artisan migrate
3. 모델 관계 설정
Post 모델과 Comment 모델 간의 관계를 설정 합니다.
// Post.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
protected $fillable = ['title', 'content'];
public function comments() {
return $this->hasMany(Comment::class);
}
}
// Comment.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
use HasFactory;
protected $fillable = ['post_id', 'content'];
public function post() {
return $this->belongsTo(Post::class);
}
}
4. 댓글 기능 컨트롤러 생성
게시글과 댓글을 관리한 컨트롤러를 생성후 컨트롤러 php파일을 열고 댓글을 조회하는 메서드를 추가합니다.
php artisan make:controller PostController
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function index()
{
// 모든 게시글과 각 게시글의 댓글을 가져옴
$posts = Post::with('comments')->get();
return view('posts.index', compact('posts'));
}
public function show($id)
{
// 특정 게시글과 댓글을 가져옴
$post = Post::with('comments')->findOrFail($id);
return view('posts.show', compact('post'));
}
}
5.라우트 설정
routes/web.php 파일에 라우트를 추가해 컨트롤러와 메서드를 연결합니다.
use App\Http\Controllers\PostController;
Route::get('/posts', [PostController::class, 'index'])->name('posts.index');
Route::get('/posts/{id}', [PostController::class, 'show'])->name('posts.show');
6. 뷰 생성
게시글과 댓글을 표시할 뷰 파일을 생성합니다.
// resources/views/posts/show.blade.php
@extends('layouts.app')
@section('content')
<h1>{{ $post->title }}</h1>
<p>{{ $post->content }}</p>
<h3>댓글:</h3>
<ul>
@foreach ($post->comments as $comment)
<li>{{ $comment->content }}</li>
@endforeach
</ul>
<a href={{ route('posts.index') }}>Back to Posts</a>
@endsection
7. 게시글 목록에 링크 추가
게시글 목록 페이지에서 게시글 생성 페이지로 이동하는 링크를 추가합니다.
// resources/views/posts/index.blade.php
<!DOCTYPE html>
<html>
<head>
<title>게시글 목록</title>
</head>
<body>
<h1>게시글 목록</h1>
<a href="{{ route('posts.create')}}">게시글 생성</a>
@foreach ($posts as $post)
<div>
<h2><a href="{{ route('posts.show', $post->id )}}">{{ $post-> title }}</a></h2>
<p>{{ $post->content }}</p>
<h3>댓글: </h3>
<ul>
@foreach ($post->comments as $comment)
<li>{{ $comment->content }}</li>
@endforeach
</ul>
</div>
@endforeach
</body>
</html>
8. 게시글에서 댓글 작성 폼 추가
게시글 상세 페이지에서 댓글을 작성하는 폼을 작성합니다.
// resources/views/posts/show.blade.php
@extends('layouts.app')
@section('content')
<h1>{{ $post->title }}</h1>
<p>{{ $post->content }}</p>
<h3>댓글:</h3>
<ul>
@foreach ($post->comments as $comment)
<li>{{ $comment->content }}</li>
@endforeach
</ul>
<h3>댓글 작성</h3>
<form action="{{ route('comments.store', $post->id) }}" method="POST">
@csrf
<div>
<label for="content">내용:</label>
<textarea name="content" id="content" require></textarea>
</div>
<button type="submit">댓글 작성</button>
</form>
<a href={{ route('posts.index') }}>Back to Posts</a>
@endsection
댓글을 처리할 컨트롤러를 생성하고 수정합니다.
php artisan make:controller CommentController
// app/Http/Controllers/CommentController.php
<?php
namespace App\Http\Controllers;
use App\Models\Comment;
use App\Models\Post;
use Illuminate\Http\Request;
class CommentController extends Controller
{
public function store(Request $request, $postId)
{
$request->validate([
'content' => 'required|string',
]);
// 여기서 수정
$post = Post::findOrFail($postId);
$post->comments()->create(['content' => $request->content]);
return redirect()->route('posts.show', $postId)->with('success', '댓글 작성 완료');
}
}
이제 routes/web.php 파일에 댓글 저장을 위한 라우트를 추가합니다.
// routes/web.php
use App\Http\Controllers\CommentController;
Route::Post('/posts/{postId}/comments', [CommentController::class, 'store'])->name('comments.store');
이제 댓글을 작성한 후 게시글 작성 페이지로 리다이렉션하고 성공 메시지를 표시하기 위해 show.blade.php에서 세션 메시지를 표시할 수 있도록 추가합니다.
// resources/views/posts/show.blade.php (수정)
<!DOCTYPE html>
<html lang="en">
<head>
<title>{{ $post-> title }}</title>
</head>
<body>
<h1>{{ $post -> title }}</h1>
<p>{{ $post->content}} </p>
<h3>댓글:</h3>
<ul>
@foreach ($post -> comments as $comment )
<li>{{ $comment->content }}</li>
@endforeach
</ul>
@if(session('success'))
<div>{{ session('success')}}</div>
@endif
<h3>
댓글 작성
</h3>
<form action="{{ route("comments.store", $post->id)}}" method="POST">
@csrf
<div>
<label for="content">내용</label>
<textarea id="content" name="content" required></textarea>
<button type="submit">댓글 작성</button>
</div>
</form>
</body>
</html>
GitHub - Koras02/laravel-bloging
Contribute to Koras02/laravel-bloging development by creating an account on GitHub.
github.com
LIST