Laravel外键“试图获取非对象的属性" [英] Laravel Foreign Key 'Trying to get property of non-object'
问题描述
我根本无法将自己的头缠在模型上.
I simply cannot wrap my head around Models.
我有两个表,users
和companies
.用户包含名为Company
的列,该列是companies
表的外键. companies表中有两列,分别是ID
和company_name
.users
下的Company
的值引用了Companies
中的ID.
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
.
我试图像这样通过外键获取company_name的值.
I am trying to get the value of company_name through the foreign key like so.
$user = User::find(1)->company->company_name;
我认为可能是错误的过程是,这(取决于模型是否正确)应该获取Company列的值,然后使用该值从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.
我的模特看起来像这样
用户
public function company() {
return $this->belongsTo('App\Company', 'company');
}
公司
protected $table = 'companies';
public function user() {
return $this->hasOne('App\User');
}
我不断得到的只是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'))
但是我不知道它是哪里的Pullyig userid
和usercompany
.
But I don't understand where it's pullyig userid
and usercompany
from.
我在做什么错了?
推荐答案
在这种情况下,您尝试获取非对象的属性,这意味着User::find(1)
或company
都不是对象.在提供的错误消息中,看起来两者之一是一个数组.
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.
查看您的基础数据库表.通常,id
是一个受保护的字段,不会在结果对象中返回. usercompany
看起来像连接字段可以交叉引用两个表(即外键).
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).
这篇关于Laravel外键“试图获取非对象的属性"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!