我有两张桌子。一个是项目,另一个是 projects_images 。每个项目都可以有很多图像。所以在这种情况下,我有一个外键 images_id 链接到项目 id
我的问题是我无法显示链接到每个项目的图像。
这是我的控制器:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Entities\Project;
use App\Entities\ProjectImage;
use DB;
class ProjectsController extends Controller
{
public function Index (){
}
public function Show($id){
$viewModel['projects'] = Project::find($id); //Finding the project
by id and passing and storing the data in projects
$pid = Project::find($id);
$viewModel['images'] = ProjectImage::where('images_id', '=', $pid)-
>orderBy('id','desc');
return view('pages.projects', $viewModel); //passing the variable to
the view
}
}
这是我的观点:
<div class="row">
@foreach($images as $image)
<img class="img-responsive" src="{{ $image->images_path }}">
@endforeach
</div>
这些是我的模态
项目
namespace App\Entities;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
protected $table = 'projects';
public function projectImage (){
return $this->hasMany('App\Entities\ProjectImage','images_id', 'id' );
}
}
另一个是 ProjectImage
<?php
namespace App\Entities;
use Illuminate\Database\Eloquent\Model;
class ProjectImage extends Model
{
protected $table = 'projects_images';
public function project (){
return $this->belongsTo('App\Entities\Project','images_id', 'id' );
}
}
我试图找出我的错误在哪里。我可以将图像保存到 projects_images 表中,并且它们正确链接到正确的项目,但是当我尝试打开项目时,我无法在视图中显示它们。
答案 0 :(得分:0)
好吧,我已经修好了。
这是正确的代码:
$viewModel['images'] = ProjectImage::where('images_id', '=', $id)->get();