简体   繁体   中英

Laravel - Dynamic binding not working in one-to-many relationship

My models are Employee, which has the relationship:

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

and Company, which has the relationship:

public function employees(){
        return $this->hasMany('App\Employee','company');
    }

company is the FK in my employees table, pointing to the id in my companies table. In tinker I run the following commands:

$employee = App\Employee::firstOrFail(); 
$employee->company; //returns 1 

But when I do

$employee->company->name; 

OR

$employee->company->id;

It returns the error:

PHP error:  Trying to get property of non-object on line 1

Thanks @Neat, the reason was that the fields were named the same as the relationship methods. I renamed the field company to company_id and it works fine now.

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