You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SQL查询需添加参数:无法获取函数中Program Id问题求助

问题:向训练计划(Program)中添加训练项(Exercise)时,查询无法获取函数参数中的Program ID

核心问题原因

查询无法获取$id参数,是因为PHP闭包的变量作用域限制:在leftjoin的匿名函数中,默认无法访问外部的$id变量,必须通过use关键字显式引入。

修正后的控制器代码

public function GetExercicesFromBDD($id) {    
    $leProgramChoisie = new ExerciceModel();
    $leProgramChoisie = $leProgramChoisie->GetProgramById($id);

    $leProgram = DB::table('ProgramToExercice')->where('IdProgram', '=', $id)->get();

    // 关键修改:在闭包中添加use($id)引入外部变量
    $mesExercices = DB::table('Exercice')
        ->leftJoin('ProgramToExercice', function ($join) use ($id) {
            $join->on('ProgramToExercice.IdExercice', '=', 'Exercice.Id')
                 ->where('ProgramToExercice.IdProgram', '=', $id);
        })
        ->whereNull('ProgramToExercice.IdProgram')
        ->get();

    // dd($mesExercices); // 调试完成后可注释或删除

    return view('addExerciceIntoProgram', [
        'mesExercices' => $mesExercices, 
        'IdProgram' => $id, 
        "leProgramChoisie" => $leProgramChoisie
    ]);
}

额外优化建议

  1. 模型方法修正:当前GetProgramById方法查询的是关联表ProgramToExercice,若要获取计划本身的信息,应修改为查询Program表:
public function GetProgramById($id) {
    // 假设计划表名为Program,根据实际表名调整
    return DB::table('Program')->where('Id', '=', $id)->first();
}

(用first()获取单条记录,而非get()返回集合,更符合"获取单个计划"的语义)

  1. 视图按钮文本翻译:将法语按钮文本替换为中文:
@foreach ($programs as $program)
    <form action="{{ url("Program/" . $program->Id . "/editExercice") }}" method="post">
        @csrf
        <button type="submit" class="btn btn-info">向计划中添加训练项</button>
    </form>
@endforeach

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 19:31:15