我先尝试了很多不同的东西,但似乎没有得到结果。
控制器:
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子句,但这并没有起作用。
任何想法如何解决这个问题?
谢谢!
答案 0 :(得分:1)
您对$ am和$ pm的查询不在foreach循环中。因此,您只获得上一个项目的$ am和$ pm值($ 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