Laravel GroupBy 和 Count 使用雄辩的模型



我有一张桌子

'new_comments'

带字段

id,user_id, title, comment_description

我还有另一个名为

'comments_upvote'

拥有

field user_id, post_id, likes

new_comments 的 ID 和表comments_upvote的 post_id 是相同的。 我们必须接受那些最喜欢的评论。 我们如何获取这些数据。

$ud = Comments_upvote::select('post_id')->groupby('post_id')- 
>orderby(DB::raw('count(likes)'), 'desc')->get();
$postid = array();
foreach ($ud as $key => $value) {
$postid[] = $value->post_id;
}
$data = DB::table('new_comments')->whereIn('id',$postid)->get();

但问题是我必须计算所有值 = 1 的喜欢,我们怎么能做到这一点。

如果你向我们展示了一些代码,你会得到一个更具体的答案,但这里有一个你需要的快速概述:定义你的关系(确保你使用你的自定义外键(,使用whereHas,按计数分组post_id,并按计数降序排序。

所以我猜你至少有两个模型NewComment和CommentUpvote(你应该(。在 NewComment 中定义 1:n 关系:

public function upvotes(){
$this->hasMany('AppCommentUpvote', 'post_id');
}

然后在您的控制器中(再次猜测,因为您没有显示任何代码(:

$bestComments = NewComment::whereHas('upvotes', function($query){
$query->select('post_id', DB::raw('count(*) as total'))->groupBy('post_id')->orderBy('total', 'desc');
})->get();

免责声明:这是未经测试的,超出了我的头顶,但应该会让你朝着正确的方向前进。

最新更新