简体   繁体   English

如果集合有数据或计数 > 0,如何获得 Eloquent 集合?

[英]How to get Eloquent collection if collection has data or count is > 0?

Consider this example... which gets the image of product.考虑这个例子......它获取产品的图像。

This function should only get the data if it exists otherwise it should return null... because it will get the images for a product otherwise the site will display a 404 not found image...这个函数应该只获取存在的数据,否则它应该返回null...因为它将获取产品的图像,否则站点将显示404未找到的图像...

// Product.php // 产品.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();
    }
}

EDIT:编辑:

Additional details额外细节

//ProductController.php //ProductController.php

public function show($slug)
{
    $product = $this->productRepository->findProductBySlug($slug);
    $productImages = $product->getFileImageURL();

    return view('pages.product.show', compact('product', 'productImages'));
}

// product/show.blade.php // 产品/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

Calling get() from Eloquent will always return to you an Eloquent collection;从 Eloquent 调用get()将始终返回一个 Eloquent 集合; which means you can use collection methods on it.这意味着您可以在其上使用收集方法。

Considering what you are wanting to do, the following should do the trick:考虑到您想要做什么,以下应该可以解决问题:

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;
}

This also saves you from having to perform an extra, unneccssary, query to get the count of records.这也使您不必执行额外的、不必要的查询来获取记录数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM