1

I have a Database with Budapest Districts in it i.e

  • I.
  • II.
  • V.
  • IV.
  • IX.

These are strings in my Database.

If I was to order by their column "region". The order is wrong.

Is there any way I can order a Laravel Collection or even write a custom "order by" for either the collection or the Database search to order by the roman numeral equivalent?

Thanks.

StuBlackett
  • 3,789
  • 15
  • 68
  • 113
  • If possible, store the `integer` equivalent alongside these and order by that. As you said, these are `string`s, and will sort alphabetically (which is obviously not the correct order for Roman Numerals). – Tim Lewis Jun 15 '20 at 15:47
  • That's not a bad idea. Thanks @TimLewis – StuBlackett Jun 15 '20 at 15:50
  • No problem! I feel like that will be the quickest/easiest solution, unless you can find some kind of PHP/SQL package for translating roman numerals to their int equivalent. Might be an interesting problem to try and solve though :) – Tim Lewis Jun 15 '20 at 15:51
  • 1
    @TimLewis Thanks for that, so solution was created a "district_numeric" column in Database. Which takes a numeric value from a PHP function that converts the string to an integer i.e V = 5. Then order by that column, works a treat – StuBlackett Jun 15 '20 at 16:02
  • Nice, and is likely much faster than trying to order by with a custom function; I'm sure the conversion is pretty quick for only a few records, but that would grind to a halt for large DB tables. Feel free to add your approach as an answer and accept it (when the system allows) to properly close this question. Cheers! – Tim Lewis Jun 15 '20 at 16:04

1 Answers1

0

by default, Laravel collection has a method called orderBy which accepts a column name. see: https://laravel.com/docs/7.x/collections#method-sortby

Another thing you mentioned for writing your custom order function can be done through extending collections. see: https://laravel.com/docs/7.x/collections#extending-collections

And finally, another thing you need to sort roman numbers is explained in detail below: How to sort an array of Roman numerals?

Soheil Rahmat
  • 491
  • 3
  • 15
  • 1
    Please don't post other answers as your own answer on Stackoverflow. If this question has already been asked and answered, add it as a comment to the original question or vote to close as a duplicate. – Tim Lewis Jun 15 '20 at 15:58