具有默认值的 Laravel 模型方法

Sve*_*art 2 php laravel eloquent laravel-5

有两张桌子

  • 产品
  • 图片(有 product_id ,优先级)

在我的产品模型中,我可以获得所有图片:

public function pictures(){
    return $this->hasMany('App\Picture');
}
Run Code Online (Sandbox Code Playgroud)

现在我想在产品中创建一个方法来获取主要图片的url(图片的product_id 的最低优先级值),如果没有结果返回一个默认值。我试过:

public function mainpicture(){
    $picture = $this->pictures()->orderBy('priority','desc')->first();
    if($picture == null)
        return 'default/default.png';
    return $picture->url;
}
Run Code Online (Sandbox Code Playgroud)

这给出了错误:

关系方法必须返回一个 Illuminate\Database\Eloquent\Relations\Relation 类型的对象

当返回一个值时,它永远不是 Illuminate\Database\Eloquent\Relations\Relation 类型,而只是一个 url。如何制作获取主图片或默认值的方法?

我想创建这个函数的原因是:因为我在很多视图中都需要它并且不想在每个视图中粘贴相同的代码。目前在我需要使用主图片的所有视图中:

@if(isset($product->pictures[0]))
    {!! Html::image('/images/product/'.$product->id.'/thumb/'.pictures[0]->url, 'Product image', array('class'=> ' img-responsive')) !!}
@else
    {!! Html::image('/images/product/default/default.png', 'No picture found', array('class'=> ' img-responsive')) !!}
@endif
Run Code Online (Sandbox Code Playgroud)

这很像意大利面条,功能会好得多。

我可以创建一个全局辅助函数,但我很好奇是否可以将它添加到我的模型中。

Tim*_*Tim 5

我知道您已经有了 Kota 的可行解决方案。但我可以建议另一种方法:

在 Laravel 中,您可以定义用于获取属性的自定义逻辑。

它们的定义如下:

public function getCustomAttribute() 
{
     return 'foo';
}
Run Code Online (Sandbox Code Playgroud)

所以在你的情况下:

public function getMainpictureAttribute()
{
    $picture = $this->pictures()->orderBy('priority')->first();
    return ($picture) ? $picture->url : 'default/path.jpg';
}
Run Code Online (Sandbox Code Playgroud)

在您看来,您现在可以访问它 $product->mainpicture

现在有多干净?并为每个产品保存一个额外的查询。