Laravel 5,使用关联/数据透视过滤数据库查询 table

Laravel 5, Filter Data Base Query using Association / Pivot table

我想要的是与项目相关联的所有行业的列表。我可以获得的是每个项目的所有行业ID,使用关联table。我无法弄清楚如何return每个Industry->Name从那些ID。

我的数据库中有三个 table:项目、projects_industries 和行业。 'projects_industries' table 有 'id'、'project_id' 和 'industries_id'。

以下代码 return 是一个空白 html 页面。感谢您的帮助/建议!

项目控制器 :

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'));
}

顺便说一句,我知道 $projectsindustries 数据库查询有效

Blade 查看 :

@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

这是我最终解决问题的方法...

数据库表和字段保持不变

项目总监

<?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 项目扩展模型 {

public function industries() {
    return $this->belongsToMany('Industry', 'projects_industries', 'projects_id', 'industries_id');
}

项目行业模型

使用Illuminate\Database\Eloquent\Model;

class ProjectIndustry 扩展模型 {

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

希望对大家有所帮助。