繁体   English   中英

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

[英]Laravel 5. Eloquent relations through several tables and behaviour in foreach

我有以下型号:

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

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

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

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

由于它具有hasMany关系,因此shopListItem将是一个需要迭代的数组:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM