gpt4 book ai didi

php - Laravel 5.6 试图获取非对象的属性

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:43:20 27 4
gpt4 key购买 nike

当我尝试回显值时,我收到异常。我用 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');
}
}

订单服务:

<?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'));

}

零件 View 首页:

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

我收到:

dd() return

但是当我尝试回显该值时,我收到了一条执行消息。

$ordem 的 dd()。

https://gist.github.com/vgoncalves13/8140a7a1bf2cb85fe4d16da20ea34acc

最佳答案

也许你的关系应该被称为cliente()假设一个订单只属于一个App\Cliente...你应该传递第三个参数是other_key...你可以通过使用英语来避免这种类型的错误(因为 laravel 会搜索 customer_id 和 order_id)

试试下面的代码

命名空间应用;

使用 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 cliente() {
return $this->belongsTo('App\Cliente', 'id', 'cliente_id');
}
}

引用:https://laravel.com/docs/5.6/eloquent-relationships#one-to-many

关于php - Laravel 5.6 试图获取非对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51119299/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com