php - Eloquent Laravel 展示试图获取非对象的属性 'code'

标签 php laravel eloquent

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

员工.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);
    }
}

当我尝试在 tinker 中向代码显示等级名称时,如下所示

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

它给我错误:

PHP Notice: Trying to get property 'code' of non-object in Psy Shell code on line 1*

表员工:

employees

成绩表:

grades

最佳答案

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

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

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

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

相关文章:

php - mysql查询未知列错误

php - 在PHP openssl_encrypt和golang河豚中匹配河豚加密

mysql - 在后端阻止连续的 SQL 请求

php - laravel 如何处理它的路由?

php - 使用 DB::raw 和 Eloquent 使用相同查询的不同结果

php - Laravel 5 orderby一对一关系

php - 简单的网页抓取 PHP Xpath DOM

php - 如何在 CodeIgniter 中检索 cookie 值?

Laravel Lighthouse Graphql HasOne 嵌套关系不起作用

mysql - 从复杂的原始 SQL 查询创建 Eloquent 模型