2016-09-20 14 views
0

私はlaravel 5アプリケーションを開発中です。 2つのデータベーステーブルから結果を取得する問題があります。ここで私が持っているものです。Laravel MySql join table

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 

私はループごとにテーブルAを返されたが、私は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

だけleftJoinjoinを置き換える:コードの

+0

あなたの答えをありがとう。だから私は両方のテーブルにすべての列を持っているので、返された列を制限する方法? –

+1

' - > select([配列としての列名]);を追加してください。上記のように –

+0

クール、ありがとうございます。私はちょうどあなたの答えを投票し、受け入れられた答えとして他の人より多くの答えを得るために選んでいない。ありがとうございました –

1

以下の行がお手伝いします一致がない場合

$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ので、空の文字列になります...

$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);