[英]Laravel Eager Loading: Sort using relationship column
I have two tables posts
and authors
the two tables have a One to Many Relationship 我有两张桌子的posts
, authors
两张桌子有一对多的关系
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 我想选择所有帖子,但按作者姓名排序, 是否可以使用Laravel的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: 如果您只想订购少量元素,则可以使用其SortBy()函数对所得集合进行订购 :
$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;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.