在Laravel 8的博客类项目中,经常需要基于文章标题找到对应文章,同时自动加载该文章下所有已审核通过的评论,避免多次查询数据库,提升接口响应效率。下面将从表结构、模型定义到具体查询实现逐步说明。

一、准备数据库表结构
首先需要有文章表和评论表,两者通过文章ID建立关联,评论表中需要包含状态字段用于区分是否已审核。以下是两张表的核心字段设计:
| 表名 | 核心字段 | 说明 |
|---|---|---|
| posts | id, title, content, created_at | 存储文章基础信息,title为文章标题字段 |
| comments | id, post_id, content, status, created_at | post_id关联文章ID,status为审核状态,1代表已审核 |
二、定义模型关联
在文章模型Post中定义与评论的关联,同时可以指定只关联已审核的评论,方便后续直接调用。
1. Post模型定义
在app/Models/Post.php中添加以下关联方法:
<?php
namespace AppModels;
use IlluminateDatabaseEloquentModel;
class Post extends Model
{
// 定义与评论的关联,只加载已审核的评论
public function approvedComments()
{
return $this->hasMany(Comment::class, 'post_id', 'id')
->where('status', 1); // status为1代表已审核
}
}
2. Comment模型定义
在app/Models/Comment.php中定义反向关联,方便从评论获取对应文章:
<?php
namespace AppModels;
use IlluminateDatabaseEloquentModel;
class Comment extends Model
{
// 定义评论所属的文章
public function post()
{
return $this->belongsTo(Post::class, 'post_id', 'id');
}
}
三、通过文章标题关联加载已审核评论
接下来实现核心逻辑,通过文章标题查询对应文章,同时自动加载该文章的已审核评论,有两种常用实现方式。
1. 使用with预加载关联
如果已经定义了approvedComments关联,可以直接通过with方法预加载:
<?php
namespace AppHttpControllers;
use AppModelsPost;
use IlluminateHttpRequest;
class PostController extends Controller
{
public function getPostWithApprovedComments(Request $request)
{
$title = $request->input('title'); // 获取传入的文章标题
// 通过标题查询文章,同时预加载已审核评论
$post = Post::where('title', $title)
->with('approvedComments')
->first();
if (!$post) {
return response()->json(['message' => '文章不存在'], 404);
}
return response()->json([
'post' => $post,
'approved_comments' => $post->approvedComments
]);
}
}
2. 未定义专用关联时的查询方式
如果没有提前定义approvedComments关联,也可以在查询时动态指定关联条件:
<?php
namespace AppHttpControllers;
use AppModelsPost;
use IlluminateHttpRequest;
class PostController extends Controller
{
public function getPostWithApprovedComments(Request $request)
{
$title = $request->input('title');
$post = Post::where('title', $title)
->with(['comments' => function ($query) {
$query->where('status', 1); // 只加载已审核的评论
}])
->first();
if (!$post) {
return response()->json(['message' => '文章不存在'], 404);
}
return response()->json([
'post' => $post,
'approved_comments' => $post->comments
]);
}
}
四、注意事项
- 文章标题查询时如果需要模糊匹配,可以将
where('title', $title)改为where('title', 'like', "%{$title}%"),但要注意性能问题,必要时可以给title字段加索引。 - 预加载关联可以有效避免N+1查询问题,如果后续需要遍历多篇文章的已审核评论,一定要使用with预加载。
- 评论的审核状态字段可以根据实际项目调整,比如用枚举值或者不同的数字代表不同状态,只需修改where条件即可。
以上就是Laravel 8中通过文章标题自动关联并加载已审核评论的完整实现方法,开发者可以根据项目实际需求选择合适的实现方式。
Laravel_8文章标题关联已审核评论加载Eloquent关联修改时间:2026-06-09 20:45:34