【问题标题】:Laravel User Auth Relationship ModelLaravel 用户认证关系模型
【发布时间】:2018-01-14 20:35:35
【问题描述】:

我怎样才能获得另一个具有身份验证登录的表?以及如何在视图中显示表的数据?我正在尝试关系,但我不知道是否正确......

class Login extends Authenticatable
{
    protected $table = "users";

    public function userProfile()
    {
        return $this->belongsTo(UserProfile::class)->select('id', 'photo', 'friendly_url');
    }

这个返回关系为空: dd(auth()->user())

Login {#307 ▼
  #table: "users"
  #relations: []

【问题讨论】:

  • 您在尝试时是否已登录?我也相信这是 Auth::user() 而不是 auth()->user()
  • @LewisJohnson 他们会做同样的事情,一个是门面,一个是 laravel 辅助方法。

标签: laravel eloquent


【解决方案1】:

模型的relations 属性仅显示加载的关系。

要为授权用户模型加载关系,请使用Eager loading

$user = auth()->user();
$user->load('userProfile');
dd($user->userProfile);

然后,您可以将视图中的用户配置文件数据引用为:

$user->userProfile->friendly_url

另外我建议您将此关系称为 profile() 而不是 userProfile() 以避免重复“用户”字样。

最好的解决方案 - 将用户配置文件数据保存在 users 表中。这要简单得多,并且在您的情况下减少了对数据库的请求数。

【讨论】:

    猜你喜欢
    • 2016-11-09
    • 2016-06-23
    • 1970-01-01
    • 2014-12-05
    • 2015-10-02
    • 2019-04-04
    • 2017-09-27
    相关资源
    最近更新 更多