Laravel - Order by as Number (int), even if column type is string
Asked Answered
F

3

15

here it is:-

$query = Section::orderBy("section", "desc")->get();

section here is a column with type string yet it is having numbers in it where i want to order by those numbers thanks for your response

Fuzzy answered 11/8, 2020 at 8:59 Comment(2)
Why have a column where you store numbers and make it a string? Just create a migration where you update the column to be a integer and then you can order by number easier.Duteous
It should work in mysql or pg. What result do you get?Goop
H
29

you can use orderByRaw with mysql convert

$query = Section::orderByRaw('CONVERT(section, SIGNED) desc')->get();
Hhour answered 11/8, 2020 at 9:14 Comment(1)
I also had this problem and your answer was useful, but in addition of string type, I have sort and sub-sort number like this : 1, 2, 3, 3-1, 3-2, 3-3, 4, 5, 5-1, 5-2 etc. with your answer everything is ok but I got sort like this : 1, 2, 3-1, 3-2, 3-3, 3, 4, 5-1, 5-2, 5 as you can see, first I see sub sortAlmire
B
4

First you should use proper data types while designing schema.

For your existing schema you can tweak your order by clause to type cast your value at runtime using orderByRaw method

->orderByRaw('section * 1 desc') 
Blueprint answered 11/8, 2020 at 9:10 Comment(0)
I
-2
$query->orderByRaw("section::int", "desc")->get();
Ingress answered 11/8, 2020 at 9:20 Comment(2)
While this code may answer the question, it would help OP and future readers more if you explain why and howImpresa
It's important to add that this only works with a full query, if you want to paginate or continue to tweek your query this won't work as intended.Heliogabalus

© 2022 - 2024 — McMap. All rights reserved.