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
Auth::user() with a relationship?
提问by user6484209
I have a regular users
table, but I also have a user_settings
table with the following relationship in my UserSettings.php
file:
我有一个普通users
表,但我的文件中还有一个user_settings
具有以下关系的表UserSettings.php
:
public function user()
{
return $this->belongsTo('App\Models\User');
}
And a settings method within my User.php
file:
和我的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_name
gives 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_name
because 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_settings
table for the particular user.
错误,因为user_settings
表中可能没有特定用户的条目。
Your relationships look correct.
你的人际关系看起来是正确的。
Just go to tinker
and find
the user for whom you are getting the error. Then try accessing the settings
for that user.
只要去tinker
和find
用户对他们来说,你所得到的错误。然后尝试访问该settings
用户的 。