Laravel计数列值为1的行

时间:2016-05-19 02:25:10

标签: php mysql laravel

嘿所以我试图做一个upvote downvote系统,我只使用1个表,表列是

var io = require('socket.io').listen(26266); // can use up to 26484
//.... imported additional modules and defined simple functions here
io.on('connection', function (socket) {  
    socket.on('restart_request', function(req){
        var success = false
            , session = JSON.parse(req.session)
            , sessionID = session.sessionID;
        checkSession(sessionID, function (ses) {
            if (ses === false) { console.error('CheckSession failed: No session exists'); return; }
            if (ses.user.uuid !== session.uuid) { console.error('CheckSession failed: UUID mismatched'); return; }
            if (ses.user.role < conf['Permissions']['lm_restart']){ socket.emit('restart_fail','Insufficient permissions.'); return; }
            if(process.platform === 'win32'){            
                executeCMD('START "" .\\windows\\scripts\\restart_lm.bat',function(err,res){
                    var errSent = false;
                    if(err){                        
                        console.error(err);
                        if(!errSent){ socket.emit('restart_fail','Restart failed'); }
                        errSent = true;
                        if(res === null){return;}
                    }
                    console.log(res);
                    socket.emit('restart_success','LM successfully restarted.');
                });                
            }
            else if(process.platform === 'linux'){

            }
        });
    });
    socket.on('get_users',function(req){
          var success = false
            , session = JSON.parse(req.session)
            , opts = req.opts || null
            , sessionID = session.sessionID
            , col = opts.col || null
            , where = opts.where || null
            , range = opts.range || null
            ;
        checkSession(sessionID, function (ses) {
            if (!ses) { console.error('CheckSession failed: No session exists'); return; }
            if (ses.user.uuid !== session.uuid) { console.error('CheckSession failed: UUID mismatched'); return; }
            if (ses.user.role < conf['Permissions']['lm_user_query']){ socket.emit('userQuery_fail','Insufficient permissions.'); return; }            
            Query.users({col: col, where: where, range: range},function(err,res){
                if(!err){socket.emit('send_users',res);}
                else {socket.emit('failed_users',true);} 
            });            
        });
    });
    socket.on('test',function(q){
        socket.emit('test',q);
    });
});

基本上我试图计算评论有多少票,但只计算 $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的反对票数

我正在考虑使用2个不同的表来执行此操作,因为它会使计数更容易,但我也不想要大型数据库。

我知道0但是这会返回总行数,而不管vote_type值如何,我想知道是否有人在保持查询较低的情况下有解决方案或知道方法。

3 个答案:

答案 0 :(得分:0)

为什么你这样做

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()->comments->where('vote_type',1)>count();

我希望你明白这一点,你不必在刀片上做计数

答案 1 :(得分:0)

我最终只创建了另一个关系,然后用主调用来接受它。例如 评论课

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 />

答案 2 :(得分:0)

回答这个问题为时已晚,但是通常在集合上使用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
});