简体   繁体   中英

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.

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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