Laravel 的所属关系 - 试图获取非对象的属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43264960/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:44:18  来源:igfitidea点击:

Laravel belongsTo relationship - Trying to get property of non-object

phplaravellaravel-5eloquentlaravel-eloquent

提问by Léo Coco

User.php

用户名.php

class User extends Authenticatable
{
    public function company() {
        return $this->belongsTo('App\Company');
    }
}

Company.php

公司.php

class Company extends Model
{
    public function users() {
        return $this->hasMany('App\User');
    }
}

Table users

表用户

id name companies_id

id 名称 company_id

Table companies

表公司

id name

身名称

I'm trying to get the name of the company attached to the user.

我正在尝试获取附加到用户的公司名称。

$user = User::findOrFail(Auth::user()->id);
$companyName = $user->company()->first()->name;

I got this error message Trying to get property of non-object

我收到此错误消息 Trying to get property of non-object

I don't get what I'm missing... Thank you in advance

我不明白我错过了什么......提前谢谢你

采纳答案by Léo Coco

By default, Eloquent is taking the name of the relationship + '_id' to guess the foreign key.

默认情况下,Eloquent 使用关系名称 + '_id' 来猜测外键。

Solution A

方案一

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

Solution B

方案B

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

回答by Turan Zamanl?

Also it may be null your company_id field

您的 company_id 字段也可能为空

That reason you must be check your field on the loop

这个原因你必须在循环中检查你的领域

f.e

foreach($users as $user) 
{
   if(isset($user->company->title)): 

     echo  $user->company->title;
   else:

     echo 'empty';
   endif;

}

回答by brunohdaniel

Try it without the "first" method.

尝试不使用“第一个”方法。

$companyName = $user->company()->name;