首页 > 解决方案 > 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

解决方案


您遇到的问题是 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');
}

推荐阅读