拉拉维尔雄辩属于关系不起作用



我正在尝试使用 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('AppDepartment' , 'department' , 'id');
}

这是访问器函数

public function getDepartmentAttribute(){
    return $this->department()->first()->name;
}

它返回以下错误消息:Undefined property: AppAjaxSearch::$department

在文档表中添加

department_id INT Foreign

在文档中迁移

$table->integer('department')->unsigned();

同时编辑关系

public function department() {
    return $this->belongsTo('AppDepartment', 'department');
}

更新

好的,根据您的更新,您可以像这样获得部门名称

$doc = Document::find(1);
$name = $doc->department->name;

您需要检查相关记录是否存在

public function department()
{
    return $this->belongsTo('AppDepartment', 'department');
}

$document是您当前的文档记录。

$name = (empty($document->department->id) === false) ? ($document->department->name) : ''; 

最新更新