【问题标题】:How to set null if relations doesn't exist?如果关系不存在,如何设置 null?
【发布时间】:2017-03-29 14:28:54
【问题描述】:

在模型中我有:

public function publisher()
{
    return $this->belongsTo('App\User', 'user_id', 'id');
}

在模板刀片中,我尝试显示数据User

@foreach($announcement->offers as $key => $item)
    <img src="{{url($item->publisher->photo)}}">
@endforeach

问题是如果User表中没有数据,程序就会崩溃,因为我无法获取$item-&gt;publisher-&gt;photo的属性。

如何解决?

【问题讨论】:

标签: laravel laravel-5.4


【解决方案1】:

你可以这样做:

@if (empty($item->publisher))
    It's empty
@else
    <img src="{{ url($item->publisher->photo) }}">
@endif

【讨论】:

  • @Daniel 为什么不呢?
  • 我会选择$item-&gt;publisher()-&gt;exists()
  • 我只会做@if($item-&gt;publisher),甚至{{ $item-&gt;publisher ? $item-&gt;publisher-&gt;name : "Unknown Publisher" }}(如果这不是一张图片的话)
  • @Neat $item-&gt;publisher-&gt;exists() 也会返回错误,因为您不能在 null 上调用 exists()
  • @Neat 很确定这将运行另一个查询;如果您已经设置了属性 (publisher),则运行另一个查询以检查它是否存在 (publisher()-&gt;exists()) 似乎效率低下。
【解决方案2】:

在这里处理内存,但你可以使用@forelse/@empty。如果您迭代的对象为空,则可以使用这些指令:

@forelse($announcement->offers as $key => $item)
    <img src="{{url($item->publisher->photo)}}">
@empty
    //default image or message?
@endforelse

https://laravel.com/docs/5.4/blade#loops

【讨论】:

  • 我认为这不太对。这只是检查$announcement-&gt;offers 是否为空,而不是ithem-&gt;publisher
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-29
  • 1970-01-01
  • 2015-09-06
  • 1970-01-01
  • 2019-09-28
  • 2016-04-05
相关资源
最近更新 更多