【问题标题】:How to get 3 conditions in laravel如何在laravel中获得3个条件
【发布时间】:2019-02-26 04:02:01
【问题描述】:

伙计们,我想在控制器 Laravel 中获得 3 个条件,所以我用评论系统建立了一个帖子。我的评论有 3 个条件,默认情况下会得到value = 0,当被批准时会得到value = 1,当被拒绝时会得到value = 2。我想获得 3 个条件来计算它的数量,因为我想为另一个条件构建另一个值,例如 value = 3 或 4 或 5,所以我不会使用 get all。

这是我的评论控制器功能代码

private function getCountComment()
{
    $user = Auth::user();
    $comcount = $user->competitions;
    foreach ($comcount as $key => $value) {
        $count = Comment::where('id_post', $value->id)
                        ->where('is_accepted', '=', 0 AND 1 AND 3)
                        ->count();
        $comcount[$key]->comment_to_count = $count;
    }
    return $comcount;
}

我尝试了该代码,但只得到第一个条件is_accepted = 0

希望你们能帮助我。

【问题讨论】:

  • 查找 whereIn()。您传递一个可能值的数组作为第二个参数。 IE: ->whereIn('is_accepted', [0, 1, 3])
  • 逻辑上应该是0 OR 1 OR 3 不是和。

标签: laravel foreach count controller conditional-statements


【解决方案1】:

试试这个代码

private function getCountComment(){
    $user = Auth::user();
    $comcount = $user->competitions;
    foreach ($comcount as $key => $value) {
        $comcount[$key]->comment_to_count = Comment::where('id_post', $value->id)->whereIn('is_accepted', [0,1,3])->count();
    }
    return $comcount;
}

或者你可以

Comment::where('id_post', $value->id)->where(function($query) {
    $query->where('is_accepted', '=', 0)
        ->orWhere('is_accepted', '=', 1)
        ->orWhere('is_accepted', '=', 3)
})->count();

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多