简体   繁体   English

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

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

I have the following Models: 我有以下型号:

Shop_list: Shop_list:

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

Shopping_list_item: Shopping_list_item:

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

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

Product: 产品:

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

When I execute this code: 当我执行此代码时:

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

I get the following correct result: 我得到以下正确结果:

  {"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"}

But if I want to loop and get id: 但是,如果我想循环获取ID:

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

Then I get the following error: 然后我得到以下错误:

Call to a member function shopListItem() on boolean

Question: Why in the loop the object is transformed to a boolean? 问题:为什么在循环中将对象转换为布尔值? What is the correct way to loop? 正确的循环方式是什么?

When you want to access the attributes of the related model, you need to use the object, not the function. 当您要访问相关模型的属性时,需要使用对象而不是函数。 Note the lack of parenthesis. 请注意缺少括号。

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

Since it's a hasMany relationship, shopListItem would be an array that you'll need to iterate through: 由于它具有hasMany关系,因此shopListItem将是一个需要迭代的数组:

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

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

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