如何对Laravel Eloquent ORM对象进行排序? [英] How to sort Laravel Eloquent ORM objects?

查看:264
本文介绍了如何对Laravel Eloquent ORM对象进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我们有一个包含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_flightsecond_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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆