php - Laravel 中的一对一关系总是需要 first() 吗?

标签 php laravel

我在 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/

相关文章:

php - 使用 jquery 正则表达式检查起始值

php - 使用 mysqli 将印地语数据插入数据库

php - 使用 Laravel 传递 URL 参数

Laravel 急切加载嵌套关系与自定义查询

php - Laravel 5.3 - 未找到 InvalidArgumentException View [索引]

php - sox的音频水印在php中不起作用

PHP 关联数组 如果表中不存在数据则插入

php - 从 Laravel 作业返回数据

php - Laravel 缓存与路由模型绑定(bind)?

php - 如何制作具有可编辑数据库结构的应用程序