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

Laravel Eloquent排序问题:同order_number按created_at倒序排序

Solution for Grouped Sorting in Laravel Query

Got it, let's tweak your Laravel query to match your exact sorting needs. The issue with your current code is that the second orderBy('updated_at', 'desc') doesn't properly group identical order_number values together before sorting within each group. Here's the fixed version:

$foos = Foo::orderBy('order_number', 'asc')
    ->orderBy('created_at', 'desc')
    ->limit(10)
    ->get();

Breakdown of the logic:

  • Primary sorting: We first sort all records by order_number in ascending order. This clusters all records with the same order_number together—like all 1s first, then all 2s, then all 3s as in your example.
  • Secondary sorting: Within each order_number group, we sort by created_at in descending order. This ensures the most recently created records show up first in each group.
  • Limit placement: The limit(10) comes after both sorting clauses, so we're pulling the top 10 records from the fully sorted dataset. This avoids the mistake of limiting before sorting, which would break the grouping entirely.

If you test this with your sample order_number sequence (1-2-3-2-3-2-1-1-1-2), you'll get exactly the output you want: all 1s grouped together (sorted by created_at desc), followed by all 2s, then all 3s.

内容的提问来源于stack exchange,提问作者Ali Özen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:22:45