Laravel 5.6尝试获取非对象的属性

Vic*_*ves 5 php foreach eager-loading laravel laravel-5

当我尝试回显值时,我收到一个例外.我用dd()检查集合,但不是null.

我的模特:

Cliente:

<?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');
    }
}
Run Code Online (Sandbox Code Playgroud)

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');
    }
}
Run Code Online (Sandbox Code Playgroud)

OrdemServicoController:

public function index()
{

    $ordens = OrdemServico::with('clientes')->get();

    return view('home',compact('ordens'));

}
Run Code Online (Sandbox Code Playgroud)

零件视图主页:

             <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>
Run Code Online (Sandbox Code Playgroud)

当我

<?php dd($ordem->clientes->nome); ?>
Run Code Online (Sandbox Code Playgroud)

我收到:

dd()返回

但是,当我尝试回应价值时,我收到了一个执行.

$ ordem的dd().

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

小智 1

也许您的关系应该被称为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');
    }
}
Run Code Online (Sandbox Code Playgroud)

<?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');
    }
}
Run Code Online (Sandbox Code Playgroud)

参考: https: //laravel.com/docs/5.6/eloquent-relationships#one-to-many