You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel博客侧边栏文章排序异常问题排查与修复

Laravel博客侧边栏文章排序异常问题解决

问题分析

你的代码存在三个核心问题导致排序异常:

  1. 最新文章排序逻辑不符:$latestPost = Post::latest()->first() 默认按 created_at 排序,而非需求中的 published_at,可能导致真正最新发布的文章未被选中作为中央展示内容。
  2. 发布时间过滤错误:whereDate('published_at', '<', Carbon::now()) 仅比较日期部分,会过滤掉当天发布的文章(比如你提到的“Doom 3”发布于2023-06-05,若当前日期也是2023-06-05,该条件会直接排除它)。
  3. 未排除重复内容:侧边栏查询未排除已作为中央展示的最新文章,可能出现重复展示的情况。

修正后的控制器代码

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 条件排除已作为中央展示的文章,避免内容重复。

额外验证建议

  1. 检查“Doom 3”的 active 字段是否为1,若为0会被过滤。
  2. 确认 published_at 字段不为空,数据库中该字段允许为null,null值会在排序中被排在最后。

内容的提问来源于stack exchange,提问作者Eduardo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 15:39:56