Laravel左连接查询

时间:2016-11-18 08:25:35

标签: laravel-5

我正在使用laravel 5.3,并且我在laravel查询方法中有一些左连接查询错误。 这是我的正常查询

 SELECT bran.branchName,sch.schoolName From m_schoolbranch bran
LEFT JOIN m_students stu ON stu.schoolNo=bran.schoolNo AND stu.branchNo=bran.branchNo  
LEFT JOIN m_school sch ON sch.schoolNo=stu.schoolNo where stu.userNo='0000000001';

这是我的新laravel查询

DB::table('m_schoolbranch')
            ->join('m_students', 'm_schoolbranch.schoolNo', '=', 'm_students.schoolNo')
            ->join('m_students', 'm_schoolbranch.branchNo', '=', 'm_students.branchNo')
            ->join('m_school', 'm_schoolbranch.schoolNo', '=', 'm_school.schoolNo')
            ->select('m_school.schoolName', 'm_schoolbranch.branchName')
            ->where('m_students.userNo',$userNo)
            ->get();

在这些查询中,我需要匹配表m_students中的两列,所以我这样放

->join('m_students', 'm_schoolbranch.branchNo', '=', 'm_students.branchNo')

但我表示错误......

2 个答案:

答案 0 :(得分:0)

查询中的表需要具有唯一的名称,否则在评估m_schoolbranch时,数据库无法知道应该使用哪个m_schoolbranch.schoolNo

您可以在连接语句中使用唯一的表别名,但我建议在连接上使用多个条件。就像您在原始SQL查询中使用一样。见这里:https://stackoverflow.com/a/20732468/4437888

答案 1 :(得分:0)

DB::table('m_schoolbranch')
            ->join('m_students', function($join)
                {
                    $join->on('m_schoolbranch.schoolNo', '=', 'm_students.schoolNo');
                    $join->on('m_schoolbranch.branchNo', '=', 'm_students.branchNo');
                })
            ->join('m_school', 'm_schoolbranch.schoolNo', '=', 'm_school.schoolNo')
            ->select('m_school.schoolName', 'm_schoolbranch.branchName')
            ->where('m_students.userNo',$userNo)
            ->get();