Laravel 外键“试图获取非对象的属性" [英] Laravel Foreign Key 'Trying to get property of non-object'

查看:31
本文介绍了Laravel 外键“试图获取非对象的属性"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我根本无法围绕模型.

我有两个表,userscompanys.用户包含一个名为 Company 的列,它是 companys 表的外键.公司表有两列,一个 IDcompany_name users 下的 Company 的值引用了 ID 中的 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 列的值,然后使用该值从 Companies 表中获取 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('AppCompany', 'company');
}

公司

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

我不断得到的只是试图获取非对象的属性

我可以在错误日志中看到它实际上也在获取公司名称!

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:wampwwwlaravelappHttpControllersHomeController.php', '41', array('userid' => '1', 'usercompany' => '1', 'company' => 'BMW')) 

但我不明白它的 pullyig useridusercompany 来自哪里.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆