I need to OrderBy a column with collection.

I need to orderBy(updated_at, 'desc') all posts which owned by current logged user.

以下是我的代码:

$posts = auth()->user()->posts->sortByDesc('updated_at');

以下是用户模型:

class User extends Authenticatable
{
    public function posts()
    {
      return $this->hasMany(Post::class);
    }
}

It doesn't return any errors also doesn't sort !

任何帮助都将不胜感激.

P.S:

我知道我可以通过以下方式实现这一点:

$posts = Post::where('user_id', auth()->user()->id)->orderBy('updated_at', 'desc')->get();

但我想对Collection 做同样的事情.

推荐答案

这就是您使用SQL进行排序的方式:

$posts = auth()->user()->posts()->orderBy('updated_at', 'DESC');

还有藏品:

$posts = auth()->user()->posts->sortByDesc('updated_at');

I've tested the 2nd one and it works as intended for me.

Documentation: https://laravel.com/docs/6.x/collections#method-sortbydesc
*Its available since Laravel 5.1

Laravel相关问答推荐

如何判断用户是否已登录Laravel

为什么Laravel在API请求时返回BadMethodCallException?

查询Laravel中的图形

使用 Laravel 10 在 Blade 中添加成功消息

前端和管理员分开时未加载laravel 9中间件

如何通过单击进入 vs 代码中的类

Laravel Eloquent 查找日期超过 2 天的行

Laravel Valet 安装后 Ping test.dev 返回未知主机

如何在 Laravel Passport 中获取刷新令牌?

Laravel 5.4 存储:下载文件.文件不存在,但显然存在

我怎样才能了解更多关于我的 Laravel 排队作业(job)失败的原因?

Laravel Request::input 调用未定义的方法

Laravel 5 - 为包创建 Artisan 命令

Laravel 字符串验证以允许空字符串

无法声明类 Controller,因为该名称已在使用中

Eloquent 模型不更新 updated_at 时间戳

如何在没有日志(log)、没有信息的情况下调试 Laravel 错误 500

Laravel Mix:更新 Node.js 依赖项

有没有办法让表名自动添加到 Eloquent 查询方法中?

Laravel:Redis 无法建立连接:[tcp://127.0.0.1:6379]