Laravel中按求和列关系排序 [英] Order by sum column relationship in Laravel
问题描述
我有这个控制器,它从发布表中获取发布. posts 表中的每个帖子与另一个表 likes 都具有"hasMany"关系.
I have this controller which grabs posts from a post table. Every post in the posts table have the relation "hasMany" with another table likes.
控制器:
public function getDashboard(){
$posts = Post::orderBy('created_at', 'desc')->get();
return view('dashboard', ['posts' => $posts]);
}
我想用以下内容代替创建于":
I'd like to replace 'created at' with something like:
$post->likes->sum(like)
虽然不知道如何编写正确的语法.
Don't know how to write the right syntax though.
这是桌子.
Posts
--id
--body
Likes
--id
--post_id
--like
like 列的值可以为1或-1. 我想为每个帖子按该列的总和排序. 因此,一个具有dislike(-1)和一个like(1)的帖子的合计值为0,因此将放置在一个具有like(1)的帖子之后.
The column like can have the value 1 or -1. I'd like to order on the summation of that column for each post. So a post with one dislike(-1) and one like(1) will have the aggregated value of 0, hence will be placed after a post with one like(1).
推荐答案
You can use withCount()
for this as:
Post::withCount('likes')->orderBy('likes_count')->get()
withCount()
将在您产生的结果上放置一个{relation} _count列 型号
withCount()
will place a {relation}_count column on your resulting models
更新
Post::withCount(['likes' => function($q) {
$q->where('like', 1)
}])
->orderBy('likes_count')
->get()
Update2
您可以使用 sortByDesc()
对您的收藏进行排序:
You can use sortByDesc()
to sort your collection as:
$posts = Post::get();
$posts = $posts->sortByDesc(function ($post) {
return $post->likes->sum('like');
});
这篇关于Laravel中按求和列关系排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!