Hello folks,
Is there a way to coerce an orderBy
clause in to return the field sorted in a natural order? I could always offload the sorting after the query using PHP's natsort
function, but would lose the benefit of skip
and limit
clauses on the resulting query (i.e., I would need to implement the effects of skip and limit in PHP as well, losing much efficiency for big relations).
I have seen some suggestions to do something like orderByRaw('LENGTH(field), field')
, but this doesn't work in my case: the contents of field are alphanumeric and aren't all like Product 1
, Product 2
, etc. There are other entries like Object with a really long name
that should appear before all Product x
, but wouldn't with the above solution.
I'd like to do something like:
Model::all()->orderByNat('field')->skip(100)->limit(10)
Any other ideas? Thanks!
A tough one - might get better responses on a mysql forum...
SELECT field+0<>0, field+0, field FROM `table` ORDER BY field+0<>0 DESC, field+0, field;
When I needed to do something similar in the past I just stuck in an extra field for sorting. When a record is saved parse the string and left pad all numbers to 6? digits with zeros. save that in the sort field and job done.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community