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


i have 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 execute code:

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

i 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 want loop , id:

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

then following error:

call member function shoplistitem() on boolean 

question: why in loop object transformed boolean? correct way loop?

when want access attributes of related model, need use object, not function. note lack of parenthesis.

{{$sh->shoplistitem->id}} 

since it's hasmany relationship, shoplistitem array you'll need iterate through:

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

Comments

Popular posts from this blog

java - Jasper subreport showing only one entry from the JSON data source when embedded in the Title band -

mapreduce - Resource manager does not transit to active state from standby -

serialization - Convert Any type in scala to Array[Byte] and back -