首页 > 解决方案 > 有人可以为我解释这个 Laravel 代码吗?

问题描述

我有一些类似下面的代码,我想问的是完全相同的// dd($example->count()) #10为什么放在dd()每条不同的行上都有不同的值?什么改变了$example我从不重新分配的事件?

$example = $car->wheels()->whereBetween(
        'created_at',
        [
            $starDay->format('Y-m-d h:i:s'),
            $today->format('Y-m-d h:i:s')
        ]
    )

$total =  $example->count();

// dd($example->count()) #10

$totalSuccess = $example->where('status', 'good')->count();

// dd($example->count()) # 5

$colors = $example->select('color', DB::raw('count(*) as total'))
        ->groupBy('color')
        ->get()
        ->toArray();

// dd($example->count()) # []

标签: phplaravellaravel-5eloquent

解决方案


值会发生变化,因为每次您向where查询中添加越来越多不同的子句(如 )。这些调用实际上更改了查询对象本身,并且更改持续存在。

  1. $example首先,您在with onlywhereBetween子句中有查询对象。它返回数据库中 10 行的计数。
  2. 然后您添加where('status', 'good')到查询中,它将选择范围缩小到 5 行。
  3. 最后,您使用和调用更改您的$example查询。select(...)groupBy()

在 Laravel 中,当您向其添加查询构造时,查询构建器对象会发生变化$example->where(...)因此,当您调用$example查询生成器对象时,现在将具有该where子句。


推荐阅读