【问题标题】:Why is this code showing $req variable undefined?为什么这段代码显示 $req 变量未定义?
【发布时间】:2021-03-29 17:39:10
【问题描述】:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class universityController extends Controller
{
    //

    public function getStudents(Request $req)
    {
        $students= DB::table('students')
        ->join('applicants', function ($join) {
            $join->on('students.id', '=', 'applicants.studentid')
                 ->where('applicants.scholarshipid','=', $req->scholarshipid);
        })
        ->get();
        return $students;
        // return $req->scholarshipid;
    }
}

【问题讨论】:

标签: php laravel controller inner-join query-builder


【解决方案1】:

使用匿名变量

$students= DB::table('students')
        ->join('applicants', function ($join) use ($req) {
            $join->on('students.id', '=', 'applicants.studentid')
                 ->where('applicants.scholarshipid','=', $req->scholarshipid);
        })
        ->get();

更多 https://www.php.net/manual/en/functions.anonymous.php

【讨论】:

    【解决方案2】:

    正如 @lagbox 提到的,你在一个匿名函数中,它无法到达外部范围 所以要解决这个问题,你需要像这样使用use

     public function getStudents(Request $req)
        {
            $students= DB::table('students')
            ->join('applicants', function ($join) use($req) {
                $join->on('students.id', '=', 'applicants.studentid')
                     ->where('applicants.scholarshipid','=', $req->scholarshipid);
            })
            ->get();
            return $students;
            // return $req->scholarshipid;
        }
    

    有关anonymous function 的更多信息,请在此处查看docs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-26
      • 2014-02-09
      • 2021-12-16
      • 2017-11-25
      • 2014-12-05
      • 1970-01-01
      相关资源
      最近更新 更多