【问题标题】:display image with relationships laravel显示具有关系 laravel 的图像
【发布时间】:2020-08-21 19:47:00
【问题描述】:

我想获取每个产品的第一张图片以将其显示到缩略图主页中。

我的代码是错误的,因为产品迭代中的关系为一个缩略图显示了一个产品的所有图像,这很丑:)。

所以我想要显示每个产品的第一张图片,因为我正在使用多张图片上传。

 Route::get('/home', function () {
    $product = Product::with('image')->get();
    dd($product);
    $image = DB::table('images')->get();
    return view('frontend.home')->with(['products' => $product,'image' => $image]);
})->name('shop.home');

此时它不起作用,因为我需要显示每个产品的第一张图片,我已经尝试过:

@foreach ($products as $product)
<img class="bd-placeholder-img"src="{{ asset("storage/{$product->image->path}") }}">
@endforeach

【问题讨论】:

  • 那么...每个产品都有很多图片?所有产品都至少有一张图片?

标签: php laravel eloquent laravel-blade


【解决方案1】:

// 产品

public function images()
{
    return $this->hasMany(Image::class);
}

在路由文件中

Route::get('/home', function () {
    $products = Product::all();
    return view('index', [$products => 'products']));
});

在刀片中:

@foreach ($products as $product)
<img src="{{ asset('storage/' . $product->images[0]->path) }}">
@endforeach

【讨论】:

    【解决方案2】:

    目前您无法获取单个记录表单 Eager 加载一对多关系,但是 您可以定义另一个hasOne 关系来获取产品的单个图​​像记录:

    public function oneImage()
    {
        return $this->hasOne('App\Image');
    }
    

    然后调用控制器:

    $product = Product::with('oneImage')->get();
    

    每个产品应该显示一张图片。

    提示:在一对多关系中,名称应该是复数,因此在您的情况下,您应该将函数命名为 images 而不是 image

    【讨论】:

      【解决方案3】:
      // Product
      public function images()
      {
          return $this->hasMany(Image::class);//don't forget to import
      }
      
      public function previewImage()
      {
          return $this->hasOne(Image::class);//don't forget to import
      }
      

      在路由文件中

      Route::get('/home', function () {
          $products = Product::with('previewImage')->get();
          return view('frontend.home', compact('products'));
      })->name('shop.home');
      

      在刀片中:

      @foreach ($products as $product)
      <img class="bd-placeholder-img"src="{{ asset('storage/' . $product->previewImage->path) }}">
      @endforeach
      

      我在这里使用了best practice and convention in framework 的一些方面来说明几个方面。研究它并适应您的应用程序。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-05-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-08
        • 2016-01-01
        • 2019-09-04
        相关资源
        最近更新 更多