You need to enable JavaScript to run this app. Laravel查询当前月用户记录时orWhere闭包参数报错如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

Laravel查询当前月用户记录时orWhere闭包参数报错如何解决?

解决方案

错误原因

1. 闭包变量作用域问题

PHP 匿名函数默认无法直接访问父作用域的变量,你在orWhere的闭包中直接使用$lastname、$name会报未定义变量的错误,需要通过use关键字将外部变量传入闭包作用域。

2. 字段拼写错误

闭包内whereMonth方法传入的字段名是dataSTOP,和你表结构里的dateSTOP不匹配,会触发SQL字段不存在的错误。

3. 查询逻辑冗余&风险

你现有写法重复书写了两次姓名匹配条件,且SQL中AND优先级高于OR,如果后续调整查询条件很容易出现逻辑漏洞,导致查询到其他用户的记录。

最优修正代码

把日期匹配规则统一放在同一个OR分组中,外层固定用户匹配条件,逻辑更清晰也避免重复代码:

public function listOfMonth(Request $request){
    $lastname = $request->get('lastname');
    $name = $request->get('name');
    $now = Carbon::now();

    $result = DB::table('timbraturas')
        ->where('lastname', $lastname)
        ->where('name', $name)
        ->where(function ($query) use ($now) {
            // 匹配dateSTART为当月的情况
            $query->whereYear('dateSTART', $now->year)
                  ->whereMonth('dateSTART', $now->month)
                  // 匹配dateSTOP为当月的情况
                  ->orWhere(function ($q) use ($now) {
                      $q->whereYear('dateSTOP', $now->year)
                        ->whereMonth('dateSTOP', $now->month);
                  });
        })
        ->orderBy('id', 'asc')
        ->get();
    return $result;
}

如果你不想调整原有逻辑结构,只需要给闭包加use导入变量,修改字段拼写即可跑通:

// 仅修复原有写法的错误
public function listOfMonth(Request $request){
    $lastname=$request->get('lastname');
    $name=$request->get('name');
    $result=DB::table('timbraturas')
            ->where('lastname',$lastname)
            ->where('name',$name)
            ->whereMonth('dateSTART','=',Carbon::now()->month)
            ->whereYear('dateSTART','=',Carbon::now()->year)
            ->orWhere(function($query) use ($lastname, $name) {
                $query->where('lastname',$lastname)
                ->where('name',$name)
                ->whereYear('dateSTOP','=',Carbon::now()->year)
                ->whereMonth('dateSTOP','=',Carbon::now()->month);
            })   
            ->orderBy('id','asc')
            ->get();
    return $result;
}

内容的提问来源于stack exchange,提问作者Saimon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 18:06:05