【发布时间】:2018-12-09 16:27:13
【问题描述】:
当我尝试回显该值时,我收到一个异常。我用 dd() 检查集合并且不为空。
我的模特:
客户:
<?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');
}
}
OrdemServico:
<?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'ing 循环中的第一项,但如果第二项没有clientes怎么办?你会看到那个异常。 -
这样使用:
optional($ordem->clientes)->nome,如果为空$ordem->clientes -
一个订单有多少个客户?如果它有多个,您应该使用
$oderm->clientes->first()->name或遍历所有客户端。 -
谢谢大家。 select * from
ordens_servicoselect * fromclienteswhereclientes.idin ('1', '2') 急切加载正在尝试查找 ID 为 1 和 2 的客户端。但我有 2 个 $orders对于同一个 $client。使用可选的,名称被回显,但第二个没有。我会弄清楚如何解决这个问题。再次感谢。你给了我一个北方,现在。
标签: php laravel laravel-5 foreach eager-loading