[英]How to get Eloquent collection if collection has data or count is > 0?
考慮這個例子......它獲取產品的圖像。
這個函數應該只獲取存在的數據,否則它應該返回null...因為它將獲取產品的圖像,否則站點將顯示404未找到的圖像...
// 產品.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
從 Eloquent 調用get()
將始終返回一個 Eloquent 集合; 這意味着您可以在其上使用收集方法。
考慮到您想要做什么,以下應該可以解決問題:
public function getFileImageURL()
{
$referType = 1; //Product = 1
$imageFileItems = File::where('file_refer_id','=', $this->id)
->where('file_refer_type','=', $referType)
->get();
return $imageFileItems->isNotEmpty()
? $imageFileItems
: null;
}
這也使您不必執行額外的、不必要的查詢來獲取記錄數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.