Laravel 5.4 Auth :: User()与关系不起作用

时间:2018-07-10 03:31:42

标签: php laravel foreign-keys relationship

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

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

enter image description here

这个数据库

enter image description here

在供应商模型中

    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);
}

2 个答案:

答案 0 :(得分:2)

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

在供应商模型中

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());

答案 1 :(得分:1)

根据讨论内容和表格结构, 在模型vendor_users中添加关联函数。

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

使用vendor_contact获取用户并检查

$user = Auth::user()->with('vendor_contact')->first(); //  As you asked with for auth
//OR
$user = Auth::user()->load('vendor_contact'); // From the rkj answer as I found this good.
// OR
$user = Vendor::find(1)->with('vendor_contact')->first(); 
dd($user);
相关问题