2016-09-20 97 views
0

我正在使用laravel 5應用程序。 我有問題從兩個數據庫表中獲取結果。這裏是我有:Laravel MySql連接表

table A: 'courses' 

id | Course 
———————————————— 
1 | Math 
2 | History 
3 | Geography 
4 | Computer 

和表B

user_id | classroom_id | course 
1  | 5   | 3 
1  | 5   | 4 
1  | 6   | 2 

我回到上一個表每個循環,但我想檢查哪些課程USER_ID 1必須返回true或false在for-each循環的每一列上。 事情是這樣的:

返回的項目爲USER_ID 1:

id | course  | status 
____________________________ 
1 | Math  | false 
2 | History | true 
3 | Geography | true 
4 | Computer | true 

這是我有:

$AllList = DB::table('users') 
      ->join('courses', 'users.id', '=', 'courses.parent_id') 
      ->join('classroom', 'users.id', '=', 'classroom.user_id')->where('classroom_id', '=', 5)  
      ->get(); 

任何幫助表示讚賞。

+1

左連接應該這樣做,如果是空的,那麼它是'假' –

+0

@ka_lin謝謝你評論,但代碼應該是什麼? –

+0

到目前爲止你有什麼? –

回答

2

只是leftJoin替換join

$AllList = DB::table('courses') 
      ->select('courses.id','course.name') 
      ->leftJoin('users', 'users.id', '=', 'courses.parent_id') 
      ->join('classroom', 'users.id', '=', 'classroom.user_id')->where('classroom_id', '=', 5)  
      ->get(); 

Course領域將是NULL從而爲空,如果沒有匹配

+0

感謝您的回答。那麼如何限制返回的列?因爲我有兩個表上的所有列。 –

+1

只需添加' - > select([列名稱作爲數組]);'就像我上面 –

+0

很酷,謝謝。我只是投了你的答案,而不是選擇接受的答案,以獲得更多的答案。再次感謝 –

1

的代碼下面的行會幫助你...

$getCourse = DB::table('courses')->get(['id','course']); 

    $getCourse = collect($getCourse)->map(function($x){ return (array) $x; })->toArray(); 

    foreach ($getCourse as $key => $value) 
    { 
     $flag = DB::table('classroom') 
        ->where('user_id',1) 
        ->where('course',$value['id']) 
        ->pluck('id'); 
     if($flag) 
     { 
      $getCourse[$key]['status'] = true; 
     } 
     else 
     { 
      $getCourse[$key]['status'] = false; 
     } 
    } 

    dd($getCourse);