Laravel:orderBy包含集合的列

Ham*_*ava 12 php laravel eloquent laravel-5.4

我需要OrderBy一个带集合的列.

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

这是我的代码:

$posts = auth()->user()->posts->sortByDesc('updated_at');
Run Code Online (Sandbox Code Playgroud)

这是用户模型:

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

它不返回任何错误也不排序!

任何帮助将非常感激.

PS:

我知道我能做到这一点:

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

但我想对收藏品做同样的事情.

Dev*_*evK 22

这就是你用SQL排序的方式:

$posts = auth()->user()->posts()->orderBy('updated_at', 'DESC');
Run Code Online (Sandbox Code Playgroud)

并收集:

$posts = auth()->user()->posts->sortByDesc('updated_at');
Run Code Online (Sandbox Code Playgroud)

我测试了第二个,它按照我的预期工作.

  • 对于任何潜伏者,如果您想通过升序排序,只需在集合上使用`sortBy()`而不是`sortByDesc()`。没有名为`sortByAsc()`的函数。 (4认同)

Ham*_*ava 6

@devk 是对的。我在第一篇文章中写的内容是正确的。

问题出在视图中的数据表中。

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

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

所以这工作正常:

$posts = auth()->user()->posts->sortByDesc('updated_at');
Run Code Online (Sandbox Code Playgroud)