2016-12-17 35 views
0

我嘗試了一堆不同的東西,但似乎沒有得到結果。Laravel - 多個外鍵和編號

控制器:

public function all() 
{ 
    $projects = Project::all(); 

    foreach($projects as $project) { 
     $pid = $project->id; 
    } 

    $am = DB::table('projects') 
     ->join('employees', 'projects.am_id', '=', 'employees.id') 
     ->where('projects.id', '=', $pid) 
     ->select('projects.id', 'projects.am_id', 'employees.name') 
     ->first(); 

    $pm = DB::table('projects') 
     ->join('employees', 'projects.pm_id', '=', 'employees.id') 
     ->where('projects.id', '=', $pid) 
     ->select('projects.id', 'projects.pm_id', 'employees.name') 
     ->first(); 

    return view('projects/all', [ 
     'projects' => $projects, 'am' => $am, 'pm' => $pm 
     ]); 
} 

查看:

<h1 class="text-center">All Projects</h1> 
      @foreach ($projects as $project) 
       <div class="row"> 
       <div class="col-md-6 text-center"> 
       <h3><a href="">{{ $project->company }}</a></h3> 
       </div> 
       <div class="col-md-6 text-center"> 
       <p>Account Manager: {{ $am->name }}</p> 
       <p>Project Manager: {{ $pm->name }}</p> 
       </div> 
       </div> 
       <hr> 
      @endforeach 

所以我要查看的公司名稱和項目經理和客戶經理對每一個項目。我所看到的雖然是所有項目的同一個人。這不是爲每個項目選擇正確的經理。

我試着在控制器中做for循環來獲取項目ID並在where子句中傳遞它,但是這沒有奏效。

任何想法如何解決這個問題?

謝謝!

回答

1

您對$ am和$ pm的查詢不在foreach循環中。所以,你只得到了$上午和下午$值的最後一個項目($ PID)

public function all() 
{ 
    $projects = Project::all(); 

    foreach($projects as $project) { 
     $pid = $project->id; 
     $am = DB::table('projects') 
      ->join('employees', 'projects.am_id', '=', 'employees.id') 
      ->where('projects.id', '=', $pid) 
      ->select('projects.id', 'projects.am_id', 'employees.name') 
      ->first(); 

     $pm = DB::table('projects') 
      ->join('employees', 'projects.pm_id', '=', 'employees.id') 
      ->where('projects.id', '=', $pid) 
      ->select('projects.id', 'projects.pm_id', 'employees.name') 
      ->first(); 
     $project->am = $am; 
     $project->pm = $pm; 
    } 


    return view('projects/all', [ 
     'projects' => $projects 
     ]); 
} 

查看

<h1 class="text-center">All Projects</h1> 
@foreach ($projects as $project) 
    <div class="row"> 
     <div class="col-md-6 text-center"> 
      <h3><a href="">{{ $project->company }}</a></h3> 
     </div> 
     <div class="col-md-6 text-center"> 
      <p>Account Manager: {{ $project->am->name }}</p> 
      <p>Project Manager: {{ $project->pm->name }}</p> 
     </div> 
    </div> 
<hr> 
@endforeach 
+0

謝謝Ravisha!我愚蠢的錯誤。 – robk27