设置关系时的laravel-4 IF循环

设置关系时的laravel-4 IF循环,laravel-4,foreign-key-relationship,Laravel 4,Foreign Key Relationship,我在我的Post模型中有这种关系 public function mainItem() { return $this->belongsTo('Item', 'item_id'); } 有些帖子已连接到项,有些帖子未连接到项 我可以用此行打印绑定状态: {{ $post->mainItem->id or 'not yet binded!'}} 我甚至可以打印通过关系传递的图像 <img src="{{ $post->mainItem->pic_fil

我在我的Post模型中有这种关系

public function mainItem()
{
    return $this->belongsTo('Item', 'item_id');
}
有些帖子已连接到项,有些帖子未连接到项

我可以用此行打印绑定状态:

{{ $post->mainItem->id or 'not yet binded!'}}
我甚至可以打印通过关系传递的图像

<img src="{{ $post->mainItem->pic_filename or ''}}">

代码适用于hasMany关系的情况,但不适用于case belongsTo。

返回的
belongsTo将是单个模型。因此,检查这一点就是检查对象
是否为空,就好像没有相关模型一样,它将返回空值

因此,正如您所说,对于a
,它有许多

@if($post->mainItem->count() > 0)
... here comes the button ...
@endif
这是属于

@if(is_null($post->mainItem))
.. Button
@endif
要找到更多的返回类型,请使用找到的API

@if(is_null($post->mainItem))
.. Button
@endif