有没有办法在 Laravel 模型中访问自己的关系属性?

Gri*_*ain 6 php model relationship laravel eloquent

我有 2 个表:usersusers_details

-- 用户有 3 列 [id,用户名,密码]

-- users_details 有 [id,user_id,name,address]

我为每个人都有模型,并具有从用户到用户详细信息的关系。

    public function details()
    {
        return $this->hasOne(UserDetails::class, 'user_id', 'id');
    }
Run Code Online (Sandbox Code Playgroud)

我的问题是:有没有办法仅以用户身份访问 UsersDetails 属性。

例如:{{ $user->name }} : {{ $user->address }} 而不是{{ $user->details->name }} : {{ $user->details->address }}

请记住,这些表只是示例,没有真正的列范围。我需要这个来实现 Laravel/Cashier 但这个插件需要 [users] 表中的 4 个新列,我想将它们放入 [users_details] 表中。

我还没有尝试过任何事情,因为我真的不知道这是否可能。除了目前,我所知道的唯一解决方法是在 User 中创建 getNameAttribute 方法:

    public function getNameAttribute()
    {
        return $this->details->name;
    }
Run Code Online (Sandbox Code Playgroud)

Dev*_*evK 3

我不确定我是否会推荐它,因为它只会为事情的运作方式增添魔力,并且从现在起 6 个月后可能很难理解。

但你可以在你的用户模型中做类似的事情。

已编辑

public function getAttribute($key)
{
    // If attribute exists on the user, return that
    return parent::getAttribute($key)
        // otherwise fallback to details attribute
        ?? optional($this->details)->getAttribute($key);
}
Run Code Online (Sandbox Code Playgroud)