我希望在我的视图中显示来自雄辩关系的数据,但我似乎做错了什么。这是我的模型关系,控制器和视图
产品
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
我该如何解决这个错误?
答案 0 :(得分:1)
在hasMany关系中,您有一个Collection作为结果,因此您应该有另一个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
。尝试这样的事情:
ionic cordova platform rm android
ionic cordova platform add android