Laravel左连接在'ON'多重条件下显示错误

时间:2015-10-28 03:32:41

标签: laravel

当我尝试在laravel中使用左连接时,我收到以下错误:

SQLSTATE [42S22]:未找到列:1054'on子句'中的未知列'$ dat'(SQL:选择studentsidstudents。{{1} } nameattendance_student来自date students attendance_student students idattendance_student student_idattendance_studentdate = $dat

基本上我想让特定日期的所有学生都参加

我的代码:

$dat = 2015-10-15;
    $student = DB::table('students')
            ->leftJoin('attendance_student', function($join)
            {
                $join->on('students.id', '=', 'attendance_student.student_id');
                $join->on('attendance_student.date', '=', $dat);
            })

            ->select('students.id', 'students.name', 'attendance_student.date'
                )
            ->get();

提供帮助

1 个答案:

答案 0 :(得分:0)

您的问题:可变范围

<强>解决方案:

$dat = 2015-10-15;
$student = DB::table('students')
        ->leftJoin('attendance_student', function($join) use ($dat)
        {
            $join->on('students.id', '=', 'attendance_student.student_id');
            $join->on('attendance_student.date', '=', $dat);
        })

        ->select('students.id', 'students.name', 'attendance_student.date'
            )
        ->get();

<强>解释

当访问在lambda函数范围之外声明的变量(function($join))时,使用use语句允许访问函数内的那些变量。

来源: http://php.net/manual/en/functions.anonymous.php