我有2个表,其中1个产品有很多prodphotos
我可以从具有相同ID的产品中检索所有prodphotos
,但我的情况是列出所有products
但仅从prodphotos
拍摄1张照片。
控制器:
public function daftarproduk()
{
$produks = Product::orderBy('created_at', 'desc')->get();
$select = Product::with('prodphotos')->firstorfail();
$photo = $select->prodphotos->pluck('photo');
$kategori = Category::orderBy('created_at', 'asc')->get();
return view('guest.daftarproduk')
->with('produks',$produks)
->with('kategori',$kategori)
->with('select',$select)
->with('photo',$photo);
}
查看:
@foreach($produks as $value)
<div class="col-xs-6 col-md-4 col-lg-3 box-product-outer">
<div class="box-product">
<div class="img-wrapper">
<a href="detail/{{$value->id}}/{{str_slug($value->name)}}">
<img alt="Product" src="images/gambarproduk/thumb_{{ i dont know what i must throw here to only get first picture }}">
</a>
</div>
<h6><a href="detail/{{$value->id}}/{{str_slug($value->name)}}">{{$value->name}}</a></h6>
</div>
</div>
@endforeach
我不知道从控制器获取$select
或$photo
的第一个照片名称时必须使用的功能。或者我的foreach
逻辑错了?请帮帮我。
答案 0 :(得分:1)
将hasOne
类型的精选照片关系添加到Product
模型中。
Product
型号
public function featuredPhoto() {
return $this->hasOne(PhotosModel);
}
在您的控制器中
public function daftarproduk()
{
// Get the products with featured image
$produks = Product::with('featuredPhoto')->orderBy('created_at', 'desc')->get();
$kategori = Category::orderBy('created_at', 'asc')->get();
return view('guest.daftarproduk')
->with('produks',$produks)
->with('kategori',$kategori);
}
查看
@foreach($produks as $value)
<div class="col-xs-6 col-md-4 col-lg-3 box-product-outer">
<div class="box-product">
<div class="img-wrapper">
<a href="detail/{{$value->id}}/{{str_slug($value->name)}}">
<img alt="Product" src="images/gambarproduk/thumb_{{ $value->featuredPhoto->photo }}">
</a>
</div>
<h6><a href="detail/{{$value->id}}/{{str_slug($value->name)}}">{{$value->name}}</a></h6>
</div>
</div>
@endforeach