[英]Laravel Count rows where column value is 1
嘿,所以我试图做一个upvote downvote系统,我只使用1个表,该表的列是
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->integer('voter_id')->unsigned();
$table->foreign('voter_id')->references('id')->on('users');
$table->boolean('vote_type')->default(0);
$table->integer('commentable_id');
$table->string('commentable_type');
$table->string('unique_vote')->unique();
基本上,我试图计算评论的票数,但仅在vote_type is == 1
,对于downvotes的反向操作(其值为0
我当时正在考虑使用2个不同的表来进行此操作,因为这样会使计数变得更加容易,但我也不想使用大型数据库。
我知道{{$comment->votes->count()}}
但是无论表决类型如何,它都会返回总行数,我想知道是否有人在保持低查询率的同时有解决方案或知道一种方法。
你为什么这样做
public function showCart() {
$votes = Vote::where('vote_type',1)->count();
// do stuff and then return the count with the actual data & view
}
你不能像这样锁链
$votes = Vote::where('vote_type',1)->where('something',$something)->count();
如果您想要登录用户的结果
$votes = Auth::user()->votes->where('vote_type',1)->count();
我希望您能明白这一点,而不必在刀片中做任何事情
回答这个问题groupBy
晚,但总的来说,按收藏进行groupBy
可能是一个不错的选择
$votesInGroups = Vote::all()->groupBy('vote_type');
如果要优化数据:
$votesInGroups->map(function($group, $key){
// assign keys so that its meaningful
if($key == 1) {
return [
'upvotes' => $group->count();
];
}
// yada yada yada
});
我最终只是创建了另一个关系,然后将其与主调用对应。 例如评论课
public function upvotes()
{
return $this->morphMany('App\Models\General\Votes', 'commentable')->whereVoteType(1);
}
public function downvotes()
{
return $this->morphMany('App\Models\General\Votes', 'commentable')->whereVoteType(0);
}
-
public function index($category_slug, $subcategory_slug, $post_slug)
{
return view('pages.forum-post', [
'post' => Post::With('comments','comments.user','comments.votes','comments.upvotes','comments.downvotes','comments.user.UserProfile')->whereSlug($post_slug)->firstOrFail()
]);
}
- 刀
@if ($comment->upvotes)
{{$comment->upvotes->count()}}
@endif
@if ($comment->downvotes)
{{$comment->downvotes->count()}}
@endif
<hr />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.