Laravel博客侧边栏文章排序异常问题排查与修复
Laravel博客侧边栏文章排序异常问题解决
问题分析
你的代码存在三个核心问题导致排序异常:
- 最新文章排序逻辑不符:
$latestPost = Post::latest()->first()默认按created_at排序,而非需求中的published_at,可能导致真正最新发布的文章未被选中作为中央展示内容。 - 发布时间过滤错误:
whereDate('published_at', '<', Carbon::now())仅比较日期部分,会过滤掉当天发布的文章(比如你提到的“Doom 3”发布于2023-06-05,若当前日期也是2023-06-05,该条件会直接排除它)。 - 未排除重复内容:侧边栏查询未排除已作为中央展示的最新文章,可能出现重复展示的情况。
修正后的控制器代码
public function index() { // 筛选已激活、已发布的最新文章,按published_at降序排序 $latestPost = Post::where('active', 1) ->where('published_at', '<=', Carbon::now()) ->orderBy('published_at', 'desc') ->first(); // 查询侧边栏文章:排除最新文章,按published_at降序取3篇 $posts = Post::where('active', 1) ->where('published_at', '<=', Carbon::now()) ->when($latestPost, function ($query) use ($latestPost) { $query->where('id', '!=', $latestPost->id); }) ->orderBy('published_at', 'desc') ->take(3) ->get(); return view('home', compact('posts', 'latestPost')); }
关键修正点说明
- 统一排序字段:中央和侧边栏的文章均使用
published_at字段排序,确保逻辑一致。 - 修正发布时间过滤:将
whereDate改为直接比较完整的datetime(where('published_at', '<=', Carbon::now())),既包含当天发布的文章,又确保只展示已到发布时间的内容。 - 排除重复文章:使用
when条件排除已作为中央展示的文章,避免内容重复。
额外验证建议
- 检查“Doom 3”的
active字段是否为1,若为0会被过滤。 - 确认
published_at字段不为空,数据库中该字段允许为null,null值会在排序中被排在最后。
内容的提问来源于stack exchange,提问作者Eduardo
相关产品推荐
相关产品推荐

