我有这个控制器,它从一个帖子表中抓取帖子。posts表中的每个帖子都与另一个表likes有关系“hasMany” 。
控制器:
public function getDashboard(){
$posts = Post::orderBy('created_at', 'desc')->get();
return view('dashboard', ['posts' => $posts]);
}
Run Code Online (Sandbox Code Playgroud)
我想用以下内容替换“创建于”:
$post->likes->sum(like)
Run Code Online (Sandbox Code Playgroud)
不知道如何编写正确的语法。
编辑:
这是桌子。
Posts
--id
--body
Likes
--id
--post_id
--like
Run Code Online (Sandbox Code Playgroud)
像列的值可以是 1 或 -1。我想对每个帖子的该列的总和进行排序。因此,具有一个不喜欢(-1)和一个喜欢(1)的帖子的聚合值为 0,因此将放置在具有一个喜欢(1)的帖子之后。
您可以将withCount()其用作:
Post::withCount('likes')->orderBy('likes_count')->get()
Run Code Online (Sandbox Code Playgroud)
withCount()将在您的结果模型上放置一个 {relation}_count 列
更新
Post::withCount(['likes' => function($q) {
$q->where('like', 1)
}])
->orderBy('likes_count')
->get()
Run Code Online (Sandbox Code Playgroud)
更新2
您可以使用sortByDesc()将您的收藏分类为:
$posts = Post::get();
$posts = $posts->sortByDesc(function ($post) {
return $post->likes->sum('like');
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4259 次 |
| 最近记录: |