在使用Carbon的Laravel / Eloquent中使用'where'时,如何“计算”

时间:2018-01-22 20:44:18

标签: php mysql laravel eloquent php-carbon

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

Blade.view

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

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

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

有人有任何想法吗?

2 个答案:

答案 0 :(得分:2)

正确的语法是:

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

答案 1 :(得分:0)

问题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;
    });
}}