我希望在我的视图中显示来自雄辩关系的数据,但我似乎做错了什么。这是我的模型关系,控制器和视图
产品
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
如何修复此错误?
在hasMany关系中,你有一个Collection作为结果,所以你应该有另一个foreach
来访问每个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