简体   繁体   中英

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

I have the following Models:

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);
}

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:

@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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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