laravel中的复杂连接

时间:2015-05-05 04:15:14

标签: php laravel laravel-4 laravel-5

我尝试进行以下复杂的连接,以获得根据学生分部开始的所有科目

$studentID  = Student::find($id);

$divisionID = Student::where('id', $studentID->id)->select('division_id')->pluck('division_id');
$payments = Payment::all();
$discounts = Discount::all();

// This the Big join to get all subjects that started according to the student's division
  $subjectStart = SubjectStart::join('teacher_subject' ,'teacher_subject.id' ,'=','subject_start.teach_sub_id')
                              ->join('subject' ,'subject.id' ,'=' , 'teacher_subject.subject_id')
                              ->join('subject_division','subject_division.subject_id' ,'=' ,'subject.id')
                              ->join('division' ,'division.id','=','subject_division.division_id')
                              ->where('division.id' ,$divisionID)
                              ->where('lecture_num' ,'>' , 0)
                              ->get();

之后我尝试循环遍历$ subjectStart,如下所示

@foreach($subjectStart as $st)
   {{$st->id}}
   {{$st->start_date}}
   {{$st->lecture_num}}
   .............
 @endforeach

除了$ st-> id之外,连接结果显示正确,显示为division_id 不是subject_start_id,例如如果除法_id = 5,循环结果超过$ subjectStart,$ st-> id将是5,5,5,.....

任何建议?

2 个答案:

答案 0 :(得分:3)

我解决了它只是使用select语句如下

// This the Big join to get all subjects that started according to the student's division
  $subjectStart = SubjectStart::join('teacher_subject' ,'teacher_subject.id' ,'=','subject_start.teach_sub_id')
                             ->join('subject' ,'subject.id' ,'=' , 'teacher_subject.subject_id')
                             ->join('subject_division','subject_division.subject_id' ,'=' ,'subject.id')
                             ->join('division' ,'division.id','=','subject_division.division_id')
                             ->where('division.id' ,$divisionID)
                             ->where('lecture_num' ,'>' , 0)
                             ->select('subject_start.id', 'subject_start.teach_sub_id', 'subject_start.group_id','subject_start.lecture_num','subject_start.start_date')
                             ->get();

答案 1 :(得分:2)

您只需使用以下代码覆盖上述代码:

  $subjectStart = SubjectStart::selectRaw('subject.start_id AS id, *')
                          ->join('teacher_subject' ,'teacher_subject.id' ,'=','subject_start.teach_sub_id')
                          ->join('subject' ,'subject.id' ,'=' , 'teacher_subject.subject_id')
                          ->join('subject_division','subject_division.subject_id' ,'=' ,'subject.id')
                          ->join('division' ,'division.id','=','subject_division.division_id')
                          ->where('division.id' ,$divisionID)
                          ->where('lecture_num' ,'>' , 0)
                          ->get();