[英]Auth::user() with a relationship?
I have a regular users
table, but I also have a user_settings
table with the following relationship in my UserSettings.php
file: 我有一个普通
users
表,但我的UserSettings.php
文件中也有一个具有以下关系的user_settings
表:
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()
获得用户的设置?
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);
}
You must set up a settings method within User model: 您必须在用户模型中设置一种设置方法:
public function settings()
{
return $this->hasOne('App\Models\Settings');
}
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. 只需去
tinker
然后find
您要获取错误的用户。 Then try accessing the settings
for that user. 然后尝试访问该用户的
settings
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.