

新闻资讯
技术学院本文介绍在 laravel 8 中无需手动传入 post_id,而是利用 eloquent 关系与 `with()` 预加载机制,根据文章标题自动获取对应文章及其已验证(verify=1)的评论,提升代码可维护性与性能。
在 Laravel 开发中,手动通过 SQL 查询(如 SELECT id FROM posts WHERE title = ?)获取 ID 再用于关联查询,不仅冗余、易出错,还违背了 Eloquent 的设计哲学。更优雅且符合 Laravel 最佳实践的方式是:正确定义模型关系 + 使用预加载(Eager Loading)。
在 app/Models/Post.php 中定义一对多关系(一个文章有多条评论):
// app/Models/Post.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = ['title', 'content', /* 其他字段 */];
// 定义与 Comment 的一对多关系
public function comments()
{
return $this->hasMany(Comment::class, 'post_id');
}
}在 app/Models/Comment.php 中定义反向关系(可选,但推荐):
// app/Models/Comment.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
protected $fillable = ['post_id', 'user_id', 'message', 'verify'];
public function user()
{
return $this->belongsTo(User::class);
}
public function post()
{
return $this->belongsTo(Post::class);
}
}将原 single() 方法中硬编码的 post_id => 7 和两次独立查询,替换为一次带条件预加载的查询:
// app/Http/Controllers/IndexController.php
public function single($title)
{
// 使用 with() 预加载 comments,并内联添加 where + orderBy 条件
$post = Post::with(['comments' => function ($query) {
$query->where('verify', 1)
->orderBy('id', 'desc');
}])->where('title', $title)->first();
// 若文章不存在,建议返回 404
if (!$post) {
abort(404, '文章未找到');
}
return view('main.single', compact('post'));
}✅ 优势说明:
修改 resources/views/main/single.blade.php,直接遍历 $post->comments:
{{-- 显示文章内容 --}}
{{ $post->title }}
{!! $post->content !!}
{{-- 渲染评论列表 --}}
@if($post->comments->count())
@foreach($post->comments as $comment)
{{ $comment->user->first_name . ' ' . $comment->user->last_name }}
{{ $comment->created_at }}
{{ $comment->message }}
@endforeach
@else
暂无已审核评论。
@endif⚠️ 注意事项:
通过以上重构,你彻底摆脱了“先查 ID、再查评论”的耦合逻辑,让代码更简洁、健壮、符合 Laravel 的约定优于配置原则。