我在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
,其中fitting
或dimmability
或light_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
中使用该参数。
答案 0 :(得分:3)
您可以使用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
答案 1 :(得分:1)
尝试一下:
$correspondingLamps = Lamp::where(['fitting' => $fitting, 'dimmability' => $dimmable])
->where(function($query) use ($lightColorCode){
$query->where(['light_color_code' => $lightColorCode]) // 2800K
->orWhere('light_color_code' => '2700K');
})
->get();