【发布时间】:2017-02-13 07:17:31
【问题描述】:
我正在尝试使用 Eloquent belongsTo 在两个表之间创建关系,但它似乎不起作用。
两张表分别是文档和部门,每个文档属于一个部门。
文件
id INT
department INT
部门
id INT
name varchar(255)
这是定义关系的函数
public function department(){
// department: foreign key
// id : departments table primary key
return $this->belongsTo('\App\Department' , 'department' , 'id');
}
这是访问函数
public function getDepartmentAttribute(){
return $this->department()->first()->name;
}
它返回以下错误消息:Undefined property: App\AjaxSearch::$department
【问题讨论】:
-
你确定 $this 是 Document 模型吗?
-
你从哪里调用这个 getDepartmentAttribute()?
-
来自一个名为
AjaxSearch的模型,它使用文档表。 -
你能把
\App\Department前面的斜线去掉,得到App\Department吗?我宁愿您不要使用引号,而只需输入Department::class,这样您就可以避免输入错误的部门模型路径,因为这会自然地影响到班级。 -
不幸的是这并没有影响任何东西,仍然得到同样的错误
标签: php sql database laravel eloquent