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_numberin ascending order. This clusters all records with the sameorder_numbertogether—like all 1s first, then all 2s, then all 3s as in your example. - Secondary sorting: Within each
order_numbergroup, we sort bycreated_atin 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
相关产品推荐
相关产品推荐

