laravel - Laravel where 和 where 或者
问题描述
我在使用where
/whereOr
查询时遇到了一些问题。我想检查是否fitting
相同dimmability
。那么light_color_code
可能是2700K
或2800K
。这是我当前的查询:
if ($lightColorCode === '2800K') {
$correspondingLamps = Lamp::where(['fitting' => $fitting, 'dimmability' => $dimmable, 'light_color_code' => $lightColorCode])
->orWhere(['fitting' => $fitting, 'dimmability' => $dimmable, 'light_color_code' => '2700K'])
->get();
}
但它会返回所有Lamps
wherefitting
或dimmability
orlight_color_code
匹配项,但它们应该都匹配。我看不出这个查询有什么问题?
更新: 正如我查看的评论中所建议的那样:https ://laravel.com/docs/5.7/queries#parameter-grouping我创建了以下查询:
$lamps = DB::table('lamps')
->where('fitting', '=', $fitting)
->where('dimmability', '=', $dimmable)
->where(function ($query, $lightColorCode) {
$query->where('light_color_code', '=', $lightColorCode)
->orWhere('light_color_code', '=', '2700K - 827 Zeer warm wit');
})
->get();
但这会返回:
函数 App\Http\Controllers\CompareController::App\Http\Controllers{closure}() 的参数太少,通过了 1 个,预期正好有 2 个
我想这是因为我$lightColorCode
作为参数传递,但我的where
.
解决方案
您可以使用 use 关键字将必要的变量从父作用域传递到闭包中。
$correspondingLamps = Lamp::where(['fitting' => $fitting, 'dimmability' => $dimmable])->where(function($query) use ($lightColorCode){
$query->where(['light_color_code' => $lightColorCode])->orWhere('light_color_code' => '2700K');})->get();
检查此以获取详细信息https://www.php.net/manual/en/functions.anonymous.php
推荐阅读
- amazon-web-services - AWS Amplify:令牌不是来自此身份池的受支持提供商
- powershell - Expand-Archive // 带有特殊字符的路径
- vue.js - 在 VueJS 中使用多个带参数的插件
- python - 使 Python 的 MariaDB 更新速度更快
- iis - 无法在 aspnet core 2.2 中将响应头连接设置为“关闭”
- vue.js - 让 v-checkbox 在 v-expansion-panel-header 中工作
- jquery - 使用 jQuery 在图像上淡入()和淡出文本的问题
- parse-platform - 在 Parse Server LiveQuery 中获取连接用户的信息
- django - 找不到单位 gunicorn.socket
- bash - 如何在特定时间后终止 watch 命令或在 bash 中为 watch 命令设置超时