当我尝试打印值时,收到了一个异常。我使用dd()检查了集合,并且不为null。
我的模型:
客户端:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Cliente extends Model
{
protected $table = 'clientes';
public function ordens() {
return $this->hasMany('App\OrdemServico','cliente_id');
}
}
工单:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class OrdemServico extends Model
{
protected $table = 'ordens_servico';
public function clientes() {
return $this->belongsTo('App\Cliente','id');
}
}
OrdemServicoController:
public function index()
{
$ordens = OrdemServico::with('clientes')->get();
return view('home',compact('ordens'));
}
部件视图主页:
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Nome Cliente</th>
<th scope="col">Modelo</th>
<th scope="col">Status O.S</th>
</tr>
</thead>
@foreach($ordens as $ordem)
<?php //dd($ordem->clientes->nome); ?>
<tr>
<th scope="row"></th>
<td>{{$ordem->id}}</td>
<td>{{$ordem->clientes->nome}}</td>
<td></td>
<td></td>
<td><button class="btn btn-outline-primary" onclick="location.href='{{ route('ordem_servico.show',1) }}'">Mostrar mais</button></td>
</tr>
@endforeach
</tbody>
</table>
当我
<?php dd($ordem->clientes->nome); ?>
我收到:
但是当我尝试打印出这个值时,我收到了一个异常。
$ordem 的 dd()。
https://gist.github.com/vgoncalves13/8140a7a1bf2cb85fe4d16da20ea34acc
$ordem
都有clientes
吗?你在循环中使用了dd
来查看第一个项目,但是如果第二个项目没有clientes
,那么你会看到异常。 - Brian Lee$ordem->clientes
为空的情况下,使用如下方式:optional($ordem->clientes)->nome
。 - Mustafa Akçakaya$order->clientes->first()->name
或循环遍历所有客户。 - Renoir Reisordens_servico
选择*从客户
,其中客户
.id
在('1','2')中渴望加载正在尝试查找ID为1和2的客户。 但是我有两个$orders用于同一个$client。使用可选项,名称被回显,但第二个没有。我会解决这个问题。 再次感谢。你给了我一个方向。 - Victor Gonçalves