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

Laravel如何按置顶日期/创建日期排序获取帖子

解决方案:实现帖子置顶的排序逻辑

你可以通过原生SQL的条件判断来实现需求,用Eloquent的orderByRaw方法就能直接嵌入逻辑:

PostModel::where('status', 1)
    ->where('moderation', 0)
    ->where('category_id', $this_category_id)
    ->orderByRaw('CASE WHEN post_top_date IS NOT NULL THEN post_top_date ELSE created_at END DESC')
    ->paginate($ElPerPageCategory);

逻辑说明:

  • 用CASE语句判断每个帖子的post_top_date字段:如果不为空,就用该字段作为排序依据;为空则使用created_at
  • 最后加DESC是让最新的置顶帖/创建帖排在前面,符合常规的帖子列表展示逻辑

如果你希望所有置顶帖(post_top_date不为空)优先排在非置顶帖前面,不管置顶日期是否早于某些帖子的创建时间,也可以用双重排序:

PostModel::where('status', 1)
    ->where('moderation', 0)
    ->where('category_id', $this_category_id)
    ->orderBy('post_top_date', 'desc')
    ->orderBy('created_at', 'desc')
    ->paginate($ElPerPageCategory);

这种方式的逻辑:

  • 先按post_top_date倒序排序,所有有置顶日期的帖子会自动排在前面(因为NULL值在排序中会被放在后面)
  • 对于没有置顶日期的帖子,再按created_at倒序排序

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 15:09:12