php - 有人可以为我解释这个 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()) # []
解决方案
值会发生变化,因为每次您向where
查询中添加越来越多不同的子句(如 )。这些调用实际上更改了查询对象本身,并且更改持续存在。
$example
首先,您在with onlywhereBetween
子句中有查询对象。它返回数据库中 10 行的计数。- 然后您添加
where('status', 'good')
到查询中,它将选择范围缩小到 5 行。 - 最后,您使用和调用更改您的
$example
查询。select(...)
groupBy()
在 Laravel 中,当您向其添加查询构造时,查询构建器对象会发生变化。$example->where(...)
因此,当您调用$example
查询生成器对象时,现在将具有该where
子句。
推荐阅读
- angular - 伊斯坦布尔突出显示 html 报告中的错误行
- dji-sdk - PanoramaMissionOperator 与 DJI Mavic Pro 和 Phantom 4 Pro 的兼容性
- flutter - IconButton的波纹效果出现在widget下方
- javascript - 我可以将 laravel 应用程序与 Gatsby.js 和 React 编写的静态网站集成吗?
- html - 如何在屏幕中间放置标签
- c - 试图用 C 写一个字母计数器
- angular - 运行业力启动时找不到入口点
- ruby-on-rails - 断开并取消订阅 Action Cable on Rails 6
- debugging - Visual Studio 2019 - 无法调试 Azure 函数 - (桌面 CLR (.NETFramework) 与托管 (CoreCLR) 调试器)
- node.js - 如何修复passport.js中的身份验证功能