我想要的是与项目相关联的所有 Industries 的列表。我可以获得的是使用关联表的每个项目的所有行业ID 。我无法弄清楚如何从这些ID返回每个 Industry-> Name 。
我的数据库中有三个表:projects,projects_industries和industries。 ' projects_industries'表格包含' id',' project_id'和' industries_id'。
以下代码返回一个空白的html页面。感谢您的帮助/建议!
ProjectsController :
public function show(Project $project){
....$projectsindustries = DB::table('projects_industries')->select('*')->where('projects_id', $project->id)->get();
....$industries = Industry::all();
....return view('projects.show', compact('project', 'projectsindustries', 'industries'));
}
BTW,我知道$ projectsindustries数据库查询工作
Blade View :
@if($projectsindustries)
....<ul>
........@foreach($projectsindustries as $projectindustry)
............@foreach($industries as $industry)
................<li><a href="#">{{ $industry::where('id', '=', '$projectindustry->industries_id')->get()->name; }}</a></li>
............@endforeach
........@endforeach
....</ul>
@else
....<p>no industries.</p>
@endif
答案 0 :(得分:0)
以下是我最终解决问题的方法......
数据库表和字段保持不变
项目控制器
<?php namespace App\Http\Controllers;
use DB;
use App\Project;
use App\ProjectIndustry;
use App\Industry;
public function show(Project $project)
{
$projectsindustries = ProjectIndustry::where('projects_id', '=', $project->id)
->join('industries', 'industries_id', '=', 'industries.id')->get();
return view('projects.show', compact('project', 'projectsindustries'));
}
项目模型
使用Illuminate \ Database \ Eloquent \ Model;
class Project扩展了Model {
public function industries() {
return $this->belongsToMany('Industry', 'projects_industries', 'projects_id', 'industries_id');
}
项目行业模式
使用Illuminate \ Database \ Eloquent \ Model;
class ProjectIndustry扩展了Model {
protected $table = 'projects_industries';
public function project()
{
return $this->belongsTo('Project', 'id', 'projects_id');
}
public function industry()
{
return $this->hasMany('Industry', 'id', 'industries_id');
}
行业模式
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Industry extends Model {
public function project()
{
return $this->belongsTo('Project');
}
}
项目视图 projects / show.blade.php
@if($projectsindustries)
<h3>Industries:</h3>
<ul>
@foreach($projectsindustries as $projectindustry)
<li><a href="{{ route('industries.show', $projectindustry->slug) }}">{{ $projectindustry->name }}</a></li>
@endforeach
</ul>
@else
<p>no industries.</p>
@endif
我希望这对某人有帮助。