7

如何在“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'  

有任何想法吗?

4

3 回答 3

11

您可以添加原始查询并执行以下操作:

Model::orderBy(DB::raw('LENGTH(text), text'));
于 2013-07-17T01:26:19.497 回答
4

对于 Laravel,这也适用:

$collection = $collection->sortBy('order', SORT_NATURAL, true);
于 2016-04-19T11:20:19.530 回答
0

排序集合(SORT_NATURAL)

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);
于 2021-09-09T11:29:46.227 回答