【问题标题】:Data for foreach loop returning empty yet there is data in the table laravel 8foreach 循环的数据返回空但表 laravel 8 中有数据
【发布时间】:2021-11-02 23:59:02
【问题描述】:

我想在页面中显示具有所有属性的产品。我正在使用每个循环来使用我在关系中定义的变量来显示数据。问题是在获取数据后无法显示数据在浏览器上。我不明白我哪里出错了。请协助。 控制器中的方法

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);
}

blade 文件中显示数据的 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>

【问题讨论】:

  • dd($merchadisedata->merchadiseattributes) 看看有没有数据
  • 你能分享一下你的商品和产品的表格结构吗?
  • @flakerimi 它显示以下 Illuminate\Database\Eloquent\Collection {#1517 ▼ #items: [] }
  • @stephenwaweru99 请发布您的表结构或迁移文件。
  • 这是产品迁移表 $table->id(); $table->string('merch_name'); $table->string('merch_code'); $table->string('merch_image'); $table->boolean('merch_isactive')->default('0');; $table->text('merch_details'); $table->string('merch_price'); $table->integer('merchcat_id'); $table->string('merch_splprice'); $table->timestamps();

标签: laravel


【解决方案1】:

您遇到的问题是 Laravel 找不到关系,因为您的 Productattribute 表中的索引名称不是 id。它是product_id。

然后你在模型中声明了新的索引名称:

return $this-&gt;hasMany(Productattribute::class, 'foreign_key', 'local_key'); 表示:

public function merchadiseattributes() 
{
    return $this->hasMany(Productattribute::class, 'product_id', 'id');
}

【讨论】:

    猜你喜欢
    • 2021-04-27
    • 1970-01-01
    • 2010-11-19
    • 2019-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-14
    • 1970-01-01
    相关资源
    最近更新 更多