2017-08-07 165 views
1

我想在我的視圖中顯示雄辯關係中的數據,但我似乎做錯了什麼。這裏是我的模型關係,控制器和視圖無法顯示與laravel的雄辯關係的數據5.4

產品

class Product extends Model 
{ 
    protected $guarded = ['id']; 

    public function prices() 
    { 
     return $this->hasMany(Price::class, 'product_id'); 
    } 
} 

價格

class Price extends Model 
{ 
    protected $guarded = ['id']; 

    public function product() 
    { 
     $this->belongsTo(Product::class); 
    } 
} 

的HomeController

public function index() 
{ 
    $products = Product::with('prices')->get(); 

    return view('home', compact('products')); 
} 

查看

@foreach ($products as $product) 
<tr> 
    <td>{{ $product->prices->date }}</td> 
    <td>{{ ucwords($product->name) }}</td> 
    <td>{{ $product->prices->cost }}</td> 
</tr> 
@endforeach 

我的觀點返回錯誤 Property [date] does not exist on this collection instance 我該如何解決此錯誤?

回答

1

In has has a lot you have a collection as result,so you should have foreach to access each Price。嘗試這樣的:

@foreach ($products as $product) 
    @foreach ($product->prices as $price) 
     <tr> 
      <td>{{ $price->date }}</td> 
      <td>{{ ucwords($product->name) }}</td> 
      <td>{{ $price->cost }}</td> 
     </tr> 
    @endforeach 
@endforeach 
+0

哇!從來不知道它是這樣的。問題解決了,謝謝。 – Mena

+0

很高興知道它的作品!你能接受答案是否正確?謝謝! – Laerte