首页 > 解决方案 > Laravel 5.4 Auth::User() 与关系不起作用

问题描述

我有 Table Vendors(用于测试 Auth 关系)和 Table Vendor_users,

但我用 Auth::user()它不是关系

在此处输入图像描述

还有这个数据库

在此处输入图像描述

在供应商模型中

    protected $table = 'vendor_users';
 public function Vendor_test(){
        return $this->belongsTo(Vendor_test::class);
    }

和 Vendor_test 模型

 protected $table = 'vendors';

public function Vendor(){
    return $this->hasMany(Vendor::class);
}

标签: phplaravelforeign-keysrelationship

解决方案


从聊天和您当前的表结构中,您应该有这样的关系

在供应商模型中

public function vendor_contact() 
{ 
  return $this->belongsTo(Vendor_contact::class, 'vendor_contact_id'); 
}

在 Vendor_contact 模型中

protected $primaryKey = 'vendContactId'; //check this 

public function vendor() 
{ 
  return $this->hasOne(Vendor::class, 'vendor_contact_id'); 
}

现在使用延迟加载来加载vendor_contact关系

Auth::user()->load('vendor_contact');
dd(Auth::user());

推荐阅读