首页 > 解决方案 > Laravel where 和 where 或者

问题描述

我在使用where/whereOr查询时遇到了一些问题。我想检查是否fitting相同dimmability。那么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();
}

但它会返回所有Lampswherefittingdimmabilityorlight_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.

标签: laraveleloquent

解决方案


您可以使用 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


推荐阅读