Laravel:使用集合按列排序

39

我需要对一个集合的某一列进行排序。

我需要按照updated_at字段,以'desc'方式对当前已登录用户拥有的所有文章进行排序。

这是我的代码:

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

这里是用户模型:

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

它没有返回任何错误,也没有排序!

任何帮助都将不胜感激。

P.S:

我知道可以使用以下方法来实现:

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

但我希望能够用集合做同样的事情。


1
尝试使用 ->latest() 替代 ->sortByDesc('updated_at'),它们是一样的。 - Onix
Method latest does not exist. - Hamed Kamrava
你需要使用 Illuminate\Database\Query\Builder - Onix
1
这并不容易:$posts = auth()->user()->posts->sortBy(function($post){return $post->updated_at;})->reverse();。这个应该可以工作。 - Autista_z
3个回答

82

所以这就是如何使用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以来可用。

11
对于任何潜水者,如果您想按升序排序,只需在集合上使用 sortBy() 而不是 sortByDesc()。没有名为 sortByAsc() 的函数。 - Chad
多个排序怎么样?我没有得到正确的数组来进行多个排序。 - Ray Coder
使用 Laravel 8,sortByAsc() 对我不起作用。 - Fernando Torres
我认为sortBy默认为升序。 - senecaTheMeek

6

@devk是对的。我在第一篇帖子中写的是正确的。

问题出在视图中的DataTables

需要将此行添加到Datatables选项中:

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

所以这个工作正常:

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

4
尝试将以下内容添加到您的用户模型中。
public function posts_sortedByDesc(){
      return $this->hasMany(Post::class)->sortByDesc('updated_at');
   }

然后通过调用 posts_sortedByDesc 而不是 posts 来获取帖子。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接