Laravel在哪里和哪里或

时间:2019-12-18 07:37:07

标签: laravel eloquent

我在where / whereOr查询中遇到了一些麻烦。我想检查fittingdimmability是否相同。那么light_color_code可以是2700K2800K。这是我当前的查询:

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,其中fittingdimmabilitylight_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中使用该参数。

2 个答案:

答案 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();