
本文详解 Laravel 8 中按分类展示文章的正确实现方式,指出常见查询逻辑错误(如漏调 get() 导致查询未执行),推荐使用 Eloquent 预加载关系提升性能,并提供完整模型、控制器与视图代码示例。
本文详解 laravel 8 中按分类展示文章的正确实现方式,指出常见查询逻辑错误(如漏调 `get()` 导致查询未执行),推荐使用 eloquent 预加载关系提升性能,并提供完整模型、控制器与视图代码示例。
在 Laravel 8 中实现「按分类展示文章」功能时,一个典型误区是:虽已正确定义 Post 与 CategoriesPost 的一对多关系,却在控制器中使用 whereHas() 构建查询后忘记执行查询——这导致 $posts 实际是一个未触发的查询构建器(Builder)实例,而非数据集合,因此视图中遍历时无任何输出。
✅ 正确做法:优先利用关联关系 + 预加载
与其手动编写复杂关联查询,不如直接通过分类模型获取其关联文章,并利用 with() 预加载避免 N+1 查询问题:
// PostController.php
public function showByCategory($slug)
{
$category = CategoriesPost::with(['posts' => function ($query) {
$query->where('article_status', 'published')
->orderBy('created_at', 'desc');
}])->where('category_slug', $slug)->firstOrFail();
return view('pages.article', [
'category' => $category,
'posts' => $category->posts, // 直接访问已预加载的 posts 关系
]);
}? 注意:firstOrFail() 替代 first() 可在分类不存在时自动返回 404,增强健壮性;with() 中的闭包用于对关联文章进一步筛选和排序。
? 模型关系确认(确保正确)
请再次核对模型中的关系定义(注意类名与外键一致性):
// app/Models/Post.php
public function category()
{
return $this->belongsTo(CategoriesPost::class, 'category_id'); // 显式指定外键更清晰
}
// app/Models/CategoriesPost.php
public function posts()
{
return $this->hasMany(Post::class, 'category_id');
}? 视图中渲染示例(resources/views/pages/article.blade.php)
<h1>{{ $category->category_name }}</h1>
@if($posts->count())
@foreach($posts as $post)
<article>
<h2>{{ $post->title }}</h2>
<p>{{ Str::limit($post->content, 150) }}</p>
<a href="{{ route('posts.show', $post) }}">阅读全文</a>
</article>
@endforeach
@else
<p>暂无已发布文章。</p>
@endif⚠️ 常见错误排查清单
- ❌ 忘记调用 ->get() 或 ->first():whereHas() 返回 Builder,不执行不会得到数据;
- ❌ 外键字段名不匹配:确保 Post 表中存在 category_id 字段,且类型与 CategoriesPost::id 一致(通常为 unsignedBigInteger);
- ❌ 数据库中 category_slug 为空或重复:检查迁移文件与种子数据是否规范;
- ❌ 路由参数未正确绑定:确认 web.php 中路由定义类似 Route::get('/category/{slug}', [PostController::class, 'showByCategory']);。
采用关系预加载方式不仅代码更简洁、可读性更强,还能显著减少数据库查询次数(从 N+1 降至 2 次),是 Laravel 开发中的最佳实践。


















