我如何 'count' 在 Laravel/Eloquent 中使用 'where' 使用 Carbon

How do I 'count' while using 'where' in Laravel/Eloquent using Carbon

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

Blade.view

{{ $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";
}

有人知道吗?

正确的语法是:

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

问题 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请求:第一个获取物品,第二个计算物品。

更好的解决方案可能是 return 仅将第一个请求的结果作为该集合的 Collection, and call the count() 方法。事实是 get() 方法调用了 Eloquent 模型查询构建器 return 集合。 \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;
    });
}}