【问题标题】:How to get Eloquent collection if collection has data or count is > 0?如果集合有数据或计数> 0,如何获得 Eloquent 集合?
【发布时间】: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

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

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

    这也使您不必执行额外的、不必要的查询来获取记录数。

    【讨论】:

    • 考虑到修改后的问题......你会做......如果图像,没有找到更好的?
    • 根据您的其他详细信息,我可能会更改您调用的方法以返回图像的图像 URL 或返回 404 URL。这样你就可以只调用一个方法并总是返回一个 URL,并且很好地隐藏了要显示的图像的逻辑。
    • 你会如何改变它?
    • 返回404 URL还是断言URL?
    • 但是当你使用 first() 访问它时它返回一个错误?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-27
    • 2021-06-01
    • 2014-01-01
    • 1970-01-01
    • 2015-08-11
    • 2021-02-14
    • 1970-01-01
    相关资源
    最近更新 更多