Laravel版本4.2
我正在尝试加入多个表并获得结果
我现在有2张桌子
1- projects_info(id - pro_title - pro_address ...)
2- projects_images(id - image - image_id)
我需要从' projects_images'中提取相关图像。其中image_id = projects_info id
这里我尝试了
这是我的路线
//Projects Route
Route::get('our-projects', 'projectController@currentProjects');
Route::get('project/{id}', 'projectController@viewProject');
//Projects details
//Route::get('project/{id}/about-project', 'projectController@viewProject');
Route::get('project/{id}/about-project', array('as' => 'about-project', 'uses' => 'projectController@viewProject'));
Route::get('project/{id}/project-images', array('as' => 'project-images', 'uses' => 'projectController@viewProjectImages'));
项目模型
class Projects extends Eloquent implements UserInterface, RemindableInterface
{
use UserTrait, RemindableTrait;
protected $table = 'project_info_arabic';
public function projectImages()
{
return $this->belongsTo('ProjectsImages', 'image_id');
}
}
ProjectsImages模型
class ProjectsImages extends Eloquent implements UserInterface, RemindableInterface
{
use UserTrait, RemindableTrait;
protected $table = 'projects_images';
public function project()
{
return $this->hasOne('Projects', 'id');
}
}
这是我的ProjectController
public function currentProjects()
{
$pro = Projects::all();
return View::make('projects.currentProjects', ['pro' => $pro]);
}
public function viewProject($id)
{
$vp = Projects::find($id);
return View::make('projects.viewProject', ['viewPro' => $vp]);
}
public function viewProjectImages($id)
{
$vpi = ProjectsImages::with('project')->get();
//$vpi = DB::table('projects_images')->select('id', 'image', 'image_id')->get();
return View::make('projects.projectDetails.projectImages', ['viewProImg' => $vpi]);
}
以下是我试图将每个页面包含在我的projectsDetails VIEW
中的方法<div class="mCustomScrollbar">
@if(Request::path()=="project/$viewPro->id/about-project")
@include('projects.projectDetails.aboutProject')
@elseif(Request::path()=="project/$viewPro->id")
@include('projects.projectDetails.aboutProject')
@elseif(Request::path()=="project/$viewPro->id/project-images")
@include('projects.projectDetails.projectImages')
@endif
</div>
并持续projectImages VIEW
<ul>
@foreach($viewProImg as $vpi)
<li class="col-sm-3 col-xs-12">
{{ HTML::image("images/projects/$vpi->image", '', array('class'=>'img-responsive')) }}
</li>
@endforeach
</ul>
我的问题
1-我得到的是表中的所有图像,它应该只是与该项目相关的图像
请提供任何帮助
答案 0 :(得分:0)
首先,项目有很多图像
public function projectImages()
{
return $this->hasMany('App\ProjectsImage');
}
..图片属于项目
public function project()
{
return $this->belongsTo('App\Project', 'project_id');
}
您应该始终参考模型。如果您指的是模型,那么您应该记住以单一形式命名模型的良好实践,如Project和ProjectImage。在Laravel中,他们希望您将表名称命名为复数,并将模型名称命名为单数。因此,如果您没有明确设置表名,它将查找模型名称加上s(ProjectS)。
然后,您可以从Project对象调用projectImages -function。所以在视图中它看起来像这样
@foreach($project->projectImages()->get() as $image)
// Do what you want with each project images
@endforeach