Laravel: orderBy 带有集合的列

Laravel: orderBy a column with collections

我需要对包含集合的列进行排序。

我需要 orderBy(updated_at, 'desc') 当前登录用户拥有的所有帖子。

这是我的代码:

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

这是用户模型:

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

没有return任何错误也没有排序!

任何帮助将不胜感激。

P.S:

我知道我可以用 :

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

但我想对集合做同样的事情。

尝试将以下内容添加到您的用户模型

public function posts_sortedByDesc(){
      return $this->hasMany(Post::class)->sortByDesc('updated_at');
   }

然后通过调用 posts_sortedByDesc 而不是 posts

来获取帖子

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

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

以及集合:

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

我已经测试了第二个,它对我来说工作正常。

文档: https://laravel.com/docs/6.x/collections#method-sortbydesc
*自 Laravel 5.1

开始可用

@devk 是对的。我在第一个post中写的是正确的。

问题出在视图的 DataTables 中。

需要将此行添加到数据表选项中:

"order": [[ 5, 'desc' ]], // 5 is the `updated_at` column (the sixth column in my case)

所以这工作正常:

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