table 数据未显示在 blade php 中
pivot table data is not showing in blade php
我有两个 tables 订单和状态。它与枢轴有关 table 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'));
现在 blade。
@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() 检查输出时它 returns 清楚但是当我想在 blade 中显示时它 returns 我试图获得 属性 'message' 的 non-object。我现在能做什么?我在另一个对我有用的项目中做到了,但现在它 returns 错误。
我的php版本:7.4
dd() 将显示第一行,然后停止执行。后一种情况将对每一行执行。您很可能在第二行或后面的行遇到没有状态的行。
$row->status()->orderBy('pivot_created_at','DESC')->first()->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
中有描述
我有两个 tables 订单和状态。它与枢轴有关 table 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'));
现在 blade。
@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() 检查输出时它 returns 清楚但是当我想在 blade 中显示时它 returns 我试图获得 属性 'message' 的 non-object。我现在能做什么?我在另一个对我有用的项目中做到了,但现在它 returns 错误。
我的php版本:7.4
dd() 将显示第一行,然后停止执行。后一种情况将对每一行执行。您很可能在第二行或后面的行遇到没有状态的行。
$row->status()->orderBy('pivot_created_at','DESC')->first()->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