Laravel Foreign Key 'Trying to get property of

2020-05-06 16:48发布

问题:

I simply cannot wrap my head around Models.

I have two tables, users and companies. Users contains a column called Company which is a foreign key to the companies table. the companies table has two columns, an ID and company_name The value of Company under users references the id in Companies.

I am trying to get the value of company_name through the foreign key like so.

$user = User::find(1)->company->company_name;

My thought process, which may be wrong, is that this (depending on if models are correct) should get the value of the Company column and then using that value, get the company_name from the Companies table.

My models look like so

User

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

Company

protected $table = 'companies';
public function user() {
    return $this->hasOne('App\User');
}

All I continuously get is Trying to get property of non-object

I can see in the error log it gives that it's actually getting the company name too!

Trying to get property of non-object', 'C:\wamp\www\laravel\app\Http\Controllers\HomeController.php', '41', array('userid' => '1', 'usercompany' => '1', 'company' => 'BMW')) 

But I don't understand where it's pullyig userid and usercompany from.

What am I doing wrong?

回答1:

In this case, you're trying to get the property of a non-object, meaning that either User::find(1) or company is not an object. In the error message provided, it looks like one of the two is an array.

Look at your underlying database tables. Generally, the id is a protected field that is not returned in the result object. usercompany looks like the concatenated field to cross-reference the two tables (i.e. the foreign key).