[英]Laravel 5. Eloquent relations through several tables and behaviour in foreach
[英]Laravel 5. How to iterate through Eloquent properties
我在Controller中具有以下功能:
public function getProduct()
{
return Product::join('shopping_list_items', 'products.id', '=', 'shopping_list_items.product_id' )
->join('shop_lists', 'shop_lists.id', '=', 'shopping_list_items.shopping_list_id')
->select('products.product_name', 'products.id')
->where('shop_lists.id', $this->id);
}
視圖中的此代碼可完美運行並顯示產品名稱:
{{$shoppinglists->getProduct()->first()->product_name}}
但是我不能像這樣循環遍歷它:
@foreach($shoppinglists->getProduct() as $sh)
{{$sh->product_name}}<br>
@endforeach
雖然它沒有顯示任何錯誤。
您的getProduct()
方法返回數據庫構建器的實例而不是集合,這就是為什么您可以執行->first()
,該方法基本上執行fetch limit 1並獲取對象。
因此,您需要調用->get()
或也許是paginate()
來實際將數據提取到數據庫並獲取對象的集合。
因此,最重要的是,只需執行以下操作:
@foreach($shoppinglists->getProduct()->get() as $sh)
{{$sh->product_name}}<br>
@endforeach
正如@Carlos解釋的那樣,您需要使用get()
從數據庫獲取值。
public function getProduct()
{
return Product::join('shopping_list_items', 'products.id', '=', 'shopping_list_items.product_id' )
->join('shop_lists', 'shop_lists.id', '=', 'shopping_list_items.shopping_list_id')
->select('products.product_name', 'products.id')
->where('shop_lists.id', $this->id)
->get();
}
這將返回一個JSON對象。 如果需要此查詢的數組輸出,請使用pluck('filed name');
而不是get();
在您看來,使用
@foreach($shoppinglists as $sh)
{{$sh->product_name}}<br>
@endforeach
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.