简体   繁体   English

Laravel雄辩的belongsTo关系不起作用

[英]Laravel Eloquent belongsTo relationship is not working

I'm trying to create a relationship between two tables using Eloquent belongsTo but it doesn't seem to work. 我正在尝试使用belongsTo在两个表之间创建一个关系,但它似乎不起作用。

the two tables are documents and departments , each document belongs to one department. 这两个表分别是文档和部门,每个文档都属于一个部门。

documents 单据

id INT
department INT

departments 部门

id INT
name varchar(255)

this is the function that defines the relationship 这是定义关系的功能

public function department(){
    // department: foreign key
    // id : departments table primary key
    return $this->belongsTo('\App\Department' , 'department' , 'id');
}

and this is the accessor function 这是访问器功能

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

it returns the following error message: Undefined property: App\\AjaxSearch::$department 它返回以下错误消息: Undefined property: App\\AjaxSearch::$department

In documents table add 在文件表中添加

department_id INT Foreign

In your documents migration 在您的文件迁移中

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

Also edit the relationship 同时编辑关系

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

Update 更新

Ok according to your updates, you can get the department name like this 确定,根据您的更新,您可以获得这样的部门名称

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

You need to check whether the related record exists 您需要检查相关记录是否存在

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

$document is your current document record. $ document是您当前的文档记录。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM