laravel 在 Eloquent 中排序时间戳

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17618896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:07:53  来源:igfitidea点击:

Sorting timestamps in Eloquent

laravellaravel-4eloquentblade

提问by Raffy Alcoriza

Newbie here in Laravel 4. Say I have a model ("Activity") that has a timestamp column, along with other metadata. When I print it out in HTML, it is arranged from earliest to latest, which won't be ideal.I want to sort it from latest to earliest, because I'm going after an activity log.

Laravel 4 中的新手。假设我有一个模型(“活动”),它有一个时间戳列以及其他元数据。我用html打印出来的时候,是从最早到最新排列的,不太理想。我想从最新到最早排序,因为我在找活动日志。

Here's the code on the view:

这是视图上的代码:

@foreach ($activities as $activity)
<tr class="activity">
    <td>{{ $activity->timestamp }}</td>
    <td>{{ $activity->activity }}</td>
</tr>
@endforeach

Here's the controller code, which arranges these stuff:

这是控制器代码,它安排了这些东西:

public function getActivity()
{
        return View::make('app.website.activity', array('activities' => Activity::all()));
}

Is there anything I can do with Activity::all() to sort it out by time?

我可以用 Activity::all() 做些什么来按时间排序吗?

Thanks!

谢谢!

回答by Altrim

If you are using the default laravel timestamps you can get the activities in descending order like this:

如果您使用默认的 Laravel 时间戳,您可以像这样按降序获取活动:

Activity::orderBy('created_at','desc')->get();

If you have manually added your timestamp column you can get them in descending order like this:

如果您手动添加了时间戳列,则可以像这样按降序获取它们:

Activity::orderBy('timestamp','desc')->get();

Hope this is what you are looking for.

希望这是你正在寻找的。