如何在“Eloquent ORM”中获得“自然秩序”?在表中,我有列“文本”(字符串)。
正常顺序:Model::orderBy('text')
'value 1'
'value 12'
'value 23'
'value 3'
'value 8'
我需要这个:
'value 1'
'value 3'
'value 8'
'value 12'
'value 23'
有任何想法吗?
您可以添加原始查询并执行以下操作:
Model::orderBy(DB::raw('LENGTH(text), text'));
对于 Laravel,这也适用:
$collection = $collection->sortBy('order', SORT_NATURAL, true);
从
1 => "...\src\storage\avatars\10.jpg"
0 => "...\src\storage\avatars\1.jpg"
2 => "...\src\storage\avatars\100.jpg"
3 => "...\src\storage\avatars\1000.jpg"
4 => "...\src\storage\avatars\101.jpg"
5 => "...\src\storage\avatars\102.jpg"
至
0 => "...\src\storage\avatars\1.jpg"
1 => "...\src\storage\avatars\10.jpg"
2 => "...\src\storage\avatars\100.jpg"
3 => "...\src\storage\avatars\101.jpg"
4 => "...\src\storage\avatars\102.jpg"
5 => "...\src\storage\avatars\1000.jpg"
$natsort_collection = $collection->sortBy(null, SORT_NATURAL)->values();
// If you work with arrays:
sort(...array of your data here..., SORT_NATURAL);