简体   繁体   中英

Laravel Eager Loading: Sort using relationship column

I have two tables posts and authors the two tables have a One to Many Relationship

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

I would like to select all posts but sort by the author's name, Is the following output achievable using Laravel's Eager Loading

[
  {
  "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"
    }
  }
]

I tried the following but it did not work:

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

If you just want to order a small amount of element, you could go and order the resulting collection with its SortBy() function:

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

Now, this isn't gonna work as expected when paginating the results.

For those cases I'd go to do it the other way around: first order the authors and then access their posts:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM