laravel - foreach 循环的数据返回空但表 laravel 8 中有数据
问题描述
我想在页面中显示具有所有属性的产品。我正在使用每个循环来使用我在关系中定义的变量来显示数据。问题是在获取数据后它无法在浏览器上显示数据.我不明白我哪里出错了..请协助。控制器中的方法
public function show($id)
{
$merchadisedata=Merchadise::find($id);
return view('backend.merchadise.productattributes')->with(compact('merchadisedata'));
}
产品模型中定义关系的变量,我在顶部导入了 productattributemodel 类
public function merchadiseattributes()
{
return $this->hasMany(Productattribute::class);
}
刀片文件中显示数据的 foreach 循环
<table id="admindatatables" class="table table-bordered display nowrap" width="100%">
<thead class="thead-dark">
<tr>
<th>Product Name </th>
<th>Attribute Size</th>
<th>Attribute Stock</th>
<th>Attribute Price</th>
<th>Attribute Sku</th>
<th>Attribute Status</th>
</thead>
<tbody>
@foreach ( $merchadisedata->merchadiseattributes as $attribute)
<tr>
<td>{{ $attribute->merchads->merch_name }}</td>
<td>{{ $attribute->productattr_size}}</td>
<td>{{ $attribute->productattr_stock }}</td>
<td>{{ $attribute->productattr_price}}</td>
<td>{{ $attribute->productattr_sku }}</td>
<td>{{ $attribute->productattr_status}}</td>
</tr>
@endforeach
</tbody>
</table>
解决方案
您遇到的问题是 Laravel 无法找到该关系,因为您的 Productattribute 表中的索引名称不是 id。它是product_id。
然后你在模型中声明了新的索引名称,如下所示:
return $this->hasMany(Productattribute::class, 'foreign_key', 'local_key');
方法:
public function merchadiseattributes()
{
return $this->hasMany(Productattribute::class, 'product_id', 'id');
}
推荐阅读
- mysql - ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) Ubuntu 20.04
- excel - VBA Selenium Chrome:如何更改链接
- html - 如何保存和使用来自输入类型收音机的数据
- java - 用于 ValueObject 层次结构的 Jackson 序列化器 - 多态
- python - 如何使用 fpdf 将表格添加到 pdf 页面中
- ubuntu - ssh 更改默认身份验证
- git - 带有壁球的 Git Workflow 短期功能分支
- python - python中的语音识别在linux中不起作用
- javascript - 如何将子组件数据传递给父组件
- javascript - WooCommerce 在使用浏览器后退按钮和页面刷新后将产品变体列表重置为第一个?