我在 User 和 UserSettings 模型之间存在一对一的关系,
但是(在 $user = auth()->user()
之后)当我尝试 $user->settings()->something
它抛出一个 Undefined property
错误。
当我使用 $user->settings()->first()->something
时它消失了...
我的问题是,这是它应该如何工作的吗?还是我做错了什么?
最佳答案
不能直接运行$user->settings()->something
.
因为当您调用 $user->settings()
, 它只是返回 Illuminate\Database\Eloquent\Relations\HasOne目的。
所以不是模型的对象,需要取模特对象并像这样调用它的属性。
$user->settings()->first()->something;
动态属性
由于您在
User
之间存在一对一的关系和 UserSettings
.如果您的用户模型中有一对一的关系:
public function settings()
{
return $this->hasOne('App\Models\UserSettings', 'user_id', 'id');
}
根据Laravel doc
Once the relationship is defined, we may retrieve the related record using Eloquent's dynamic properties. Dynamic properties allow you to access relationship methods as if they were properties defined on the model:
Eloquent will automatically load the relationship for you, and is even smart enough to know whether to call the get (for one-to-many relationships) or first (for one-to-one relationships) method. It will then be accessible via a dynamic property by the same name as the relation.
所以可以用eloquent的dynamic properties像这样:
$user->settings->something; // settings is the dynamic property of $user.
关于php - Laravel 中的一对一关系总是需要 first() 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59781859/