提问者:小点点

Laravel渴望加载:使用关系列排序


我有两个表文章作者这两个表有一个一对多的关系

posts table
id    title    author_id
1     Post 1   1
2     Post 2   2
3     Post 3   1

authors table
id    name
1     A
2     B

我想选择所有的帖子,但按作者的名字排序,以下输出是否可以使用Laravel的急切加载实现

[
  {
  "id": 1,
  "title": "Post 1",
  "author_id": 1,
    "author": {
    "id": 1,
    "name": "A"
    }
  },
  {
  "id": 3,
  "title": "Post 3",
  "author_id": 1,
    "author": {
    "id": 1,
    "name": "A"
    }
  },
  {
  "id": 2,
  "title": "Post 2",
  "author_id": 2,
    "author": {
    "id": 2,
    "name": "B"
    }
  }
]

我尝试了以下方法,但无效:

Post::with(['author' => function($query){
    $query->orderBy('name', 'asc');
}])->get();

共1个答案

匿名用户

如果您只想订购少量元素,可以使用其SortBy()函数对生成的集合进行订购:

$posts = Post::with('author')
         ->get()
         ->sortBy(function ($post) {
             return $post->author->name;
         });

现在,在分页结果时,这不会像预期的那样起作用。

对于这些情况,我会采取另一种方式:首先对作者进行排序,然后访问他们的帖子:

$authors = Author::with('posts')->orderBy('name')->get();

$posts = $authors->map(function ($author) {
    return $author->posts;
});