【问题标题】:How do I 'count' while using 'where' in Laravel/Eloquent using Carbon如何在 Laravel/Eloquent 中使用 Carbon 使用“where”时“计数”
【发布时间】:2018-07-01 13:51:42
【问题描述】:

我想计算使用以下代码得到的输出:

刀片视图

{{ $kentekens->where('created_at', '>=', Carbon::today()) }}

这给出了字符串的输出,但我想计算它获得的匹配数量。 我尝试了以下但没有成功:

{{ $kentekens->where('created_at', '>=', Carbon::today()->count()) }}

{{ $kentekens->count()->where('created_at', '>=', Carbon::today()) }}

控制器

public function create() {
    $kentekens = Kenteken::latest()
        ->get();

    return view('layouts.dashboard', compact('kentekens'));
}

型号

class Kenteken extends Model {
    protected $table = "kenteken";
}

有人知道吗?

【问题讨论】:

    标签: php mysql laravel eloquent php-carbon


    【解决方案1】:

    正确的语法是:

    {{ $kentekens->where('created_at', '>=', Carbon::today())->count() }}
    

    【讨论】:

    • 跟进问题,如果我还想在需要特定首字母的地方计算它们怎么办。我看到了这样的东西但没有用: {{ $kentekens->where('created_at', '>=', Carbon::today())->where('kenteken', 'LIKE', 'B%')->count() }}
    • @JesseyFransen 您只能在查询数据库时使用like。当您像这里一样使用集合时,您需要使用带有闭包的 filter() 方法。
    • 我还是有点新。能不能给我一个更详细的答案?
    【解决方案2】:

    问题 1

    一种解决方案是将两个变量从控制器添加到视图中:

    控制器

    public function create() {
        $kentekensQuery = Kenteken::latest()->where('created_at', '>=', Carbon::today());
    
        return view('layouts.dashboard')
            ->with('kentekens', $kentekensQuery->get())
            ->with('kentekensCount', $kentekensQuery->count());
    }
    

    查看

    {{ $kentekens }}
    {{ $kentekensCount }}
    

    但是这个方法发出两个sql请求:第一个是获取物品,第二个是计数。

    更好的解决方案是仅将第一个请求的结果作为Collection 返回,然后对该集合调用count() 方法。事实上,在 Eloquent 模型查询构建器上调用的 get() 方法会返回一个 Collection。 \o/

    控制器

    public function create() {
        $kentekens = Kenteken::latest()->where('created_at', '>=', Carbon::today();
    
        return view('layouts.dashboard')
            ->with('kentekens', $kentekens->get());
    }
    

    查看

    {{ $kentekens }}
    {{ $kentekens->count() }}
    

    问题 2

    有了上面的第一个解决方案:

    控制器

    $kentekensQuery = Kenteken::latest()
         ->where('created_at', '>=', Carbon::today())
         ->where('kenteken', 'LIKE', 'B%');
    

    使用第二种解决方案,正如@Alexei Mezenin 所说,您必须使用闭包,一个在使用函数迭代集合上的每个值时运行的函数,这里是filter() 函数:

    查看

    {{
        $kentekens->filter(function ($value, $key) {
            return strpos($value, 'B') === 0;
        });
    }}
    

    【讨论】:

      猜你喜欢
      • 2019-04-17
      • 1970-01-01
      • 1970-01-01
      • 2017-09-28
      • 2016-01-27
      • 1970-01-01
      • 1970-01-01
      • 2015-10-26
      • 1970-01-01
      相关资源
      最近更新 更多