Laravel 5.通过几个表格和foreach中的行为雄辩的关系

时间:2016-09-07 17:54:19

标签: php laravel eloquent

我有以下型号:

Shop_list:

public function shopListItem()
{
    return $this->hasMany(Shopping_list_item::class, 'shopping_list_id');
}

Shopping_list_item:

public function shoppingList()
{
    return $this->belongsTo(Product::class);
}

public function product()
{
    return $this->belongsTo(Product::class);
}

产品:

public function shopListItem()
{
    return $this->hasMany(Shopping_list_item::class);
}

执行此代码时:

{{$shoppinglists->shopListItem()->first()}}

我得到以下正确结果:

  {"id":1,"shopping_list_id":13,"product_id":69,"quantity":4,"created_at":"2016-09-05 19:23:35","updated_at":"2016-09-05 19:34:53"}

但如果我想循环并获得id:

@foreach($shoppinglists as $sh)
{{$sh->shopListItem()->id}}
@endforeach

然后我收到以下错误:

Call to a member function shopListItem() on boolean

问题:为什么在循环中对象被转换为布尔值?循环的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

如果要访问相关模型的属性,则需要使用对象,而不是函数。注意缺少括号。

{{$sh->shopListItem->id}}

由于它是hasMany关系,shopListItem将是您需要迭代的数组:

@foreach($sh->shopListItem AS $item)
{{ $item->id }} 
@endforeach