Laravel Select 来自 HasMany 关系的第一行

Laravel Select the First Row From HasMany Relation

我有 2 个 table,其中 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 逻辑错了?请帮助我。

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