【问题标题】:Laravel Count rows where column value is 1Laravel 计算列值为 1 的行数
【发布时间】:2019-11-28 03:32:21
【问题描述】:

嘿,所以我正在尝试做一个 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 的投票数,以及值为0 的downvotes 的反面

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

我知道{{$comment->votes->count()}},但无论 vote_type 值如何,它都会返回总行数,我想知道是否有人有解决方案或知道一种方法,同时保持低查询。

【问题讨论】:

  • 我不知道 laravel,但我敢打赌它在查询中有一个 ->where() 函数,允许您过滤行。

标签: php mysql laravel


【解决方案1】:

你为什么这样做

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();

我希望你明白这里的意思,你不必在刀片中进行计数

【讨论】:

  • 如果有数千个 cmets 每个都有投票,这是否会在前端添加数千个查询?
【解决方案2】:

回答这个问题为时已晚,但总的来说 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
});

【讨论】:

    【解决方案3】:

    我最终只是创建了另一个关系,然后将其加入主调用。例如 cmets类

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

    【讨论】:

    • 你应该通过 sql 101,只是为了理解你在数据库级别上的逻辑。
    • 我知道我做了 2 次查询来检查同一个数据库并拉出所有行只是为了得到一个计数,我可以在其中采摘说... id。但至少这比对每个评论进行 2 次查询要好。我对我对论坛页面的 6 个查询感到满意。
    猜你喜欢
    • 1970-01-01
    • 2021-10-11
    • 1970-01-01
    • 2022-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-07
    • 2013-08-24
    相关资源
    最近更新 更多