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
相关产品推荐
相关产品推荐

