如何对Laravel Eloquent ORM对象进行排序? [英] How to sort Laravel Eloquent ORM objects?
问题描述
例如,我们有一个包含3个字段的模型航班:
For example, we have a model flight having 3 fields:
- created_at:航班创建的时间
- 名称:航班的名称
- 得分:航班得分
所以我这样写:
$flights = App\Flight::orderBy('created_at');
我得到了一些由create_time
排序的$flight
对象.所以我将航班名称由create_time
更改为first_flight
,second_flight
,依此类推...
I get some $flight
objects ordered by create_time
. So I will change the name of flight by create_time
to first_flight
, second_flight
and so on...
但是我想显示按分数排序的$flights
.因此,我必须按得分对$flights
进行排序,但我不知道如何实现.
But I want to display $flights
sorted by score. So I have to sort $flights
by score, but I have no idea how to achieve that.
所以我的问题是,如何按字段对雄辩的ORM对象排序(在我的示例中为score
)?
So my question is, how to sort Eloquent ORM objects by a field(in my example, it's score
)?
推荐答案
只需获取一个集合:
$flights = App\Flight::all();
然后使用 sortBy()
或
And then sort it with sortBy()
or sortByDesc()
without hitting DB:
$filghts->sortBy('created_at');
....
$filghts->sortBy('score');
这篇关于如何对Laravel Eloquent ORM对象进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!