10

I have two columns, quarter_number and quarter_year. The quarter_number column stores a value between 1 and 4, while quarter_year stores a year value. I want the data to be sorted like so for example:

ex: (quarter_number - quarter_year)
4 - 2015
3 - 2015
2 - 2015
1 - 2015
4 - 2014
3 - 2014
etc...

Thus it seemed like this statement would work:

$last_figures = QuarterData::where('company_id', '=', $company->id) ->orderBy('quarter_number')->orderBy('quarter_year')->get();

Unfortunately, it doesn't seem to work as intended (which I thought would be similar to a radix sort). It ends up just sorting by the year (or whatever to last orderBy statement is). Do I have to just program my own custom radix sort for this? Or is there a better way?

Thank you.

jrgilman
  • 460
  • 1
  • 4
  • 15
  • Does this answer your question? [How to sort a Laravel query builder result by multiple columns?](https://stackoverflow.com/questions/17006309/how-to-sort-a-laravel-query-builder-result-by-multiple-columns) – mickmackusa Oct 30 '22 at 21:04

1 Answers1

22

I think you have to use the quarter_year first, like this:

$last_figures = QuarterData::where('company_id', '=', $company->id)
       ->orderBy('quarter_year')->orderBy('quarter_number')->get();
Alex
  • 4,674
  • 5
  • 38
  • 59
  • 1
    That seems to have been it. I wonder why this works and the other doesn't. – jrgilman Jan 05 '16 at 01:04
  • I think what you actually want is - `$last_figures = QuarterData::where('company_id', '=', $company->id) ->orderBy('quarter_year', 'desc')->orderBy('quarter_number', 'desc)->get();` which will order your data in reverse i.e. 2015,2014,2013,etc. – dino Jan 05 '16 at 01:08
  • Also you need to order by `quarter_year` first so that you get the grouping that you require, i.e. order by the year first and then by the quarter to get the quarter numbers grouped by year. – dino Jan 05 '16 at 01:12
  • I want it to order from oldest to newest, but yes that would work too. My original post makes it look like I want it DESC though. – jrgilman Jan 05 '16 at 03:15