[英]Eloquent Laravel show Trying to get property 'code' of non-object
我有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
:
更改您的grades()
的方法, Employee
模型grade()
Eloquent使用方法名称来确定用于关系的数据库列。 如果您将列名更改为grades_id
或者您可以选择在关系上定义列,则它也会起作用:
public function grades()
{
return $this->belongsTo(Grade::class, 'grade_id');
}
请加with
和尝试:
$a = App\Employee::with('grades')->find(15);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.