【问题标题】:pivot table data is not showing in blade php数据透视表数据未显示在刀片​​ php 中
【发布时间】:2021-05-19 06:02:46
【问题描述】:

我有两个表订单和状态。它与数据透视表 order_status 相关

在我的Order 模型中

public function status()
{
    return $this->belongsToMany('App\Status')->withTimestamps();
}

在我的Status 模型中

public function order()
{
    return $this->belongsToMany('App\Order')->withTimestamps();
}

在控制器中

$items = Order::orderBy('id','desc')->with('status')->paginate(20);

return view('dashboard.index', compact('items'));

现在在刀片中。

@foreach($items as $key=>$row)
{{-- {{ dd($row->status()->orderBy('pivot_created_at','DESC')->first()->message ) }} --}} //it works if checked by dd()
    <tr>
        <td>{{ $row->status()->orderBy('pivot_created_at','DESC')->first()->message }}</span></td> //here it not works and says Trying to get property 'message' of non-object
    </tr>
@endforeach

请检查我的代码。我再次重复我的问题。当我通过 dd() 检查输出时,它会清楚地返回,但是当我想在刀片中显示时,它会返回我尝试获取非对象的属性“消息”。我现在能做什么?我在另一个对我有用的项目中做到了,但现在它返回错误。

我的 php 版本:7.4

【问题讨论】:

    标签: php laravel laravel-blade


    【解决方案1】:

    dd() 将显示第一行,然后停止执行。后一种情况将针对每一行执行。您很可能会在第二行或后面的行中遇到没有状态的行。

    $row-&gt;status()-&gt;orderBy('pivot_created_at','DESC')-&gt;first()-&gt;message 是一行相当密集的代码,其中发生了许多事情。为了帮助准确了解出了什么问题,您应该将其分成几行并添加一些检查以处理此类事情。第一次运行可能看起来像这样:

    $statuses = $row->status()->orderBy('pivot_created_at','DESC');
    if ($statuses->count() > 0) {
       <td>{{ $statuses->first()->message }}</td>
    }
    

    也就是说,一个更清晰的长期解决方案可能是查看模型中关系定义可用的withDefault 功能,这在https://laravel.com/docs/8.x/eloquent-relationships 上进行了描述

    【讨论】:

      猜你喜欢
      • 2021-09-22
      • 2015-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-08
      • 2021-10-17
      • 1970-01-01
      • 2016-08-15
      相关资源
      最近更新 更多