【发布时间】:2020-05-22 02:24:13
【问题描述】:
考虑这个例子......它获取产品的图像。
这个函数应该只在数据存在的情况下获取数据,否则它应该返回 null...因为它将获取产品的图像,否则网站将显示 404 未找到图像...
// Product.php
public function getFileImageURL()
{
$referType = 1; //Product = 1
if(File::where('file_refer_id','=', $this->id)
->where('file_refer_type','=', $referType)
->count()>0)
{
return $imageFileItems = File::where('file_refer_id','=', $this->id)
->where('file_refer_type','=', $referType)
->get();
}
}
编辑:
更多细节
//ProductController.php
public function show($slug)
{
$product = $this->productRepository->findProductBySlug($slug);
$productImages = $product->getFileImageURL();
return view('pages.product.show', compact('product', 'productImages'));
}
// 产品/show.blade.php
@if($productImages)
<a href=" {{ $productImages->first()->file_url }}" data-lightbox="product-images" data-alt="{{ $productImages->first()->title }}" data-title="{{ $productImages->first()->name }}"><img src="{{ $productImages->first()->file_url }}"></a>
@else
<a href="#"><img alt="Image not found" src="{{ asset('images/products/404.png') }}"></a>
@endif
【问题讨论】: