【问题标题】:Eloquent Laravel show Trying to get property 'code' of non-object雄辩的 Laravel 节目试图获取非对象的属性“代码”
【发布时间】:2018-09-30 04:00:12
【问题描述】:

我创建了 2 个模型,如下所示:

Employee.php

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Employee extends Model
{
    public function grades(){
        return $this->belongsTo(Grade::class);
    }
}

还有

Grade.php

<?php

namespace App;
use Illuminate\Database\Eloquent\Model;

class Grade extends Model
{
    public function employee(){
        return $this->hasMany(Employee::class);
    }
}

当我尝试在修补程序中显示代码名称时,如下所示

$a=App\Employee::find(15);<br>
$a->grades->code

它给了我错误:

PHP 通知:试图在第 1 行* 的 Psy Shell 代码中获取非对象的属性“代码”

table employees:

table grades:

【问题讨论】:

  • 你能提供正在使用的迁移吗?

标签: php laravel eloquent


【解决方案1】:

Employee 模型中的grades() 方法更改为grade()

Eloquent 使用方法名称来确定要用于关系的数据库列。如果您将列名更改为 grades_id 或者您有选择地在关系上定义列,它也会起作用,如下所示:

public function grades() 
{
    return $this->belongsTo(Grade::class, 'grade_id');
}

【讨论】:

  • 哇,我不知道它有效,它是关于复数的吗?你能解释一下吗?
  • @Goon 复数方法名称(即grades)有很多关系。单数方法名称(即grade)用于属于您只期望单个结果的关系。
【解决方案2】:

请添加with 并尝试:

$a = App\Employee::with('grades')->find(15);

【讨论】:

  • App\Employee {#2950 id: 15, code: "19610202", name: "Adzull", grade_id: 11, position: "a Position", created_at: null, updated_at: null, grades: null, }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-12
  • 1970-01-01
  • 2015-09-22
  • 2017-03-20
  • 2014-03-25
  • 2015-01-25
相关资源
最近更新 更多