2016-09-08 18 views
1

I持ってコントローラーに次の関数:Laravel 5.

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 

エラーは表示されませんが、

+1

を使用し、追加 - >(GET); – Carlos

+0

ありがとう! get()の有無にかかわらずオブジェクトの違いを説明できますか? –

+0

違いは、それがなければ、それは事ではないということです。 - > get();クエリを実行してオブジェクトを返すように指示します。 – Lynne

答えて

1

getProduct()メソッドは、コレクションではなくデータベースビルダーのインスタンスを返します。そのため、->first()は基本的にフェッチ制限1を実行し、オブジェクトを取得します。

したがって、->get()またはおそらくpaginate()を呼び出して、実際にデータベースにデータを取得し、オブジェクトのコレクションを取得する必要があります。

だから、一番下の行は、単に実行します。

@foreach($shoppinglists->getProduct()->get() as $sh) 
    {{$sh->product_name}}<br> 
@endforeach 
1

を@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オブジェクトを返します。このクエリから配列出力が必要な場合は、あなたのビューでは代わりにget();pluck('filed name');を使用し、場所後

@foreach($shoppinglists as $sh) 
{{$sh->product_name}}<br> 
@endforeach