簡體   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