laravel Auth::user() 有关系吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37902725/
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 14:01:20  来源:igfitidea点击:

Auth::user() with a relationship?

laravellaravel-5laravel-5.2

提问by user6484209

I have a regular userstable, but I also have a user_settingstable with the following relationship in my UserSettings.phpfile:

我有一个普通users表,但我的文件中还有一个user_settings具有以下关系的表UserSettings.php

public function user()
{
    return $this->belongsTo('App\Models\User');
}

And a settings method within my User.phpfile:

和我的User.php文件中的设置方法:

public function settings()
{
    return $this->hasOne('App\Models\UserSettings');
}

I want to be able to access the user and their settings by doing Auth::user(), but doing Auth::user()->settings->column_namegives me an error:

我希望能够通过执行 访问用户及其设置Auth::user(),但执行Auth::user()->settings->column_name给我一个错误:

Trying to get property of non-object

试图获取非对象的属性

How can I get the user's settings using Auth::user()?

如何使用 获取用户的设置Auth::user()

回答by Codearts

You can access it like so:

您可以像这样访问它:

var_dump(Auth::user()->settings);

You cannot access it like so Auth::user()->settings->column_namebecause you have to foreach it.

你不能像这样访问它,Auth::user()->settings->column_name因为你必须 foreach 它。

foreach(Auth::user()->settings as $setting) {
     var_dump($setting->column_name);
}

回答by Sergeon

You must set up a settings method within User model:

您必须在 User 模型中设置一个设置方法:

public function settings()
{
    return $this->hasOne('App\Models\Settings');
}

回答by linuxartisan

You must be getting

你一定会得到

Trying to get property of non-object

试图获取非对象的属性

error as there may be no entry in user_settingstable for the particular user.

错误,因为user_settings表中可能没有特定用户的条目。

Your relationships look correct.

你的人际关系看起来是正确的。

Just go to tinkerand findthe user for whom you are getting the error. Then try accessing the settingsfor that user.

只要去tinkerfind用户对他们来说,你所得到的错误。然后尝试访问该settings用户的 。